Question: Part 2: Assertions Background: This one is not in the video. It is in the book, or you can dig for an explanation online. The
Part 2: Assertions
Background:
This one is not in the video. It is in the book, or you can dig for an explanation online.
The assert keyword was added to Java in version 1.2. That caused a problem. assert was used for many years in C++, and when Java did not provide that mechanism, many Java programmers added a public method called assert into their code. When Java 1.2 came out, all of the code that used assert wouldnt compile, because they had a method name that matched a keyword.
assert somethingTrue; // does nothing
assert somethingThatIsFalse; // this will throw an AssertionError
It became necessary to add some qualifiers to the compile and run commands in Java, so that assertions might be used at compile time and/or at run time. Since we are doing all of our work within Eclipse, you will need to figure out how to turn these on within the Eclipse environment. Eclipse is generating the commands to compile and run the java programs thats good, we dont have to type the commands, but it makes it harder when we need to change what command is generated.
The compile and run switches for Assertions are quite elaborate. Assertions are only used during development. Everyone will want to turn off this feature at run-time when the product is released.
When you have figured out how to turn Assertions on / off within Eclipse, post your solution on the discussion board. If the answer is already there, but you can add something, do it. You dont need to re-post something that is already there.
Coding exercise:
Demonstrate using the assert keyword. Create a private method that takes an int parameter.
If the value passed in is negative, the method will assert something that is false, causing the method to throw an AssertionError.
Pass the value that was passed into the method to the constructor of the AssertionError class.
All of this is done with a single assert statement.
Why did I ask you to make this method private? It works the same with public methods. Put a comment in the code if you can find an answer that question. (It isnt something you can figure out, you will need to read about the convention and the reason for having that convention.)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
