Please give me some details with at least one example.
An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.
Check out links below for more details and examples -
http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html
http://www.roseindia.net/javacertification/scjp5/assertionsexample.shtml
Try this:
public class AssertionTest {
public static void main(String args[]) {
boolean assertTest = true;
assert assertTest;
assertTest = false;
assert assertTest;
}
}
If you compile and run this, you should have an idea of how the assertion statement works.
Update:
As correctly pointed out in the comments, after compilation, you run this as java -ea AssertionTest
- the -ea
flag enables assertions.
You use the assert
keyword to verify if something you believe about your code is true.
The assertion in not a substitute for code validations, because it can be disabled at runtime ( it is disabled by default ) So, if the assertion is disabled and you use it to control your logic, you'll have undesired results.
For instance:
class SomeClass {
public void someMethod( String input ) {
// do something with the input...
String result = processs( input );
assert result.startWith("OK");
// continue with your code..
return result;
}
....
}
In that code, the program does something with the input. Your assumption is, that the result string starts with "OK"
always. You put the assertion, to make sure that happens, but you don't put any logic around that ( you don't do anything if that doesn't happens )
When you're testing your code, with assertion enabled, if you notice your result doesn't start with "OK", then the program will stop it's execution.
To enable/disble assertions, you have to pass the flag -ea
to the java
See : http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html for more information.