Possible Duplicate:
What does assert do?
Please give me some details with at least one example.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With