Answer
assert is the keyword added in the java 1.4. assert tests the programers assumption during development without writing exception handlers for an exception. suppose you assumed that a number passed into a method will always be positive. while testing and debugging, you want to validate your assumption. without the assert keyword you write a method will do the above is,
private void method(int a) { if(a>=0) { //do all stuff } else { //print error } }
this is the simple exception handling consider the case of big one. assertion will be come into the picture when you don't want to take the time to write the exception handling code.
cosider the above program with assertion
private void method(int a) { assert (a>=0) //throws an assertion error.
//do stuff }
in this program assert (a>0) will pass when 'a' is only positive. if the value of 'a' is negative then, the assertion error was thrown.
there are two types of assertion are there.
1)simple
2)Really simple.
example for really simple assertion
private void method() { assert (x>0) //do more stuff }
example for really simple
private void method() { assert (x>0) : "X is" + x ; // do more stuff }
the difference between these two is, the simple assertion adds the second expression.
note: assertion code - in effect - evaporates when the program is deployed.
for assertion first you need to invoke the assertion.
Answer
Actually, "assert" doesn't fo anything:
-*- mode: compilation; default-directory: "~/java/twister/" -*- javac OctVertex.java OctVertex.java:35: warning: as of release 1.4, assert is a keyword, and may not be used as an identifier assert (lat.axis != orient.axis); ^ OctVertex.java:35: cannot resolve symbol symbol : method assert (boolean) location: class Twist assert (lat.axis != orient.axis); ^ 1 error 1 warning
Answer
Even though your compiler suggested it was using version 1.4, it wasn't actually because you compiled using the "javac [files]" command instead of the "javac -source 1.4 [files]" command. Assertions only work in version 1.4.
First answer by sathishkumar palaniappan. Last edit by ID416112122. Question popularity: 47 [recommend question]





