Assertion in Java: Legal and illegal assert statements
Valid/Invalid Assertion expression
1) assert (x > =0);
2) assert (x > =0): "X is a negative number:"+x;
exp1 exp2
The second expression can be anything that results in a value. Remember, the second expression is used to generate a String message that displays in the stack trace to give you a little more debugging information. It works much like System.out.println() in that you can pass it a primitive or an object, and it will convert it into a String representation. It must resolve to a value!
-------------------------------------------------------------------------------------------------------
class AssertTest { // (for example)
void noReturnValue() { }
int aReturnValue() { return 1; }
void assertTest() {
int x = 1;
boolean b = true;
// the following six are legal assert statements
assert(x == 1);
assert(b);
assert true;
assert(x == 1) : x;
assert(x == 1) : aReturnValue();
assert(x == 1) : new ValidAssert();
assert(x = 1); // none of these are booleans
assert(x);
assert 0;
assert(x == 1) : ; // none of these return a value
assert(x == 1) : noReturnValue();
assert(x == 1) : ValidAssert va;
}
}
--------------------------------------------------------------------------------------------------
Comments
Post a Comment