Can java's assert statement allow you to specify a message? Can java's assert statement allow you to specify a message? java java

Can java's assert statement allow you to specify a message?


You certainly can:

assert x > 0 : "x must be greater than zero, but x = " + x;

See Programming with Assertions for more information.


assert (condition) : "some message";

I'd recommend putting the conditional in brackets

assert (y > x): "y is too small. y = " + y;

Imagine if you came across code like this...

assert isTrue() ? true : false : "some message";

Don't forget this has nothing to do with asserts you'd write in JUnit.


It absolutely does:

assert importantVar != null : "The important var was null!";

This will add "The important var was null" to the exception that is thrown.