korujzade korujzade - 1 year ago 50
Java Question

Why aren't the println message printing when it is inside the method used as assert error message?

When I run the code below with

java -ea Test
command, the output is:

bar Exception in thread "main" java.lang.AssertionError: 7
at Test.main(Test.java:11)

public class Test
public static int bar(int z)
System.out.print("bar ");
return z;

public static void main(String [] args )
assert false : bar(7);
System.out.println("done ");

I am wondering why I can't see
in the output.

Answer Source

I am not sure if you have fully understood how assert works. What you do is you assert the boolean expression false which is (no surprise) false and causes the assertion to fail. Then you call bar(7) and the return value is used as error message. It doesn't make much sense to me but it works technically as expected. And actually there is a "bar" at the beginning of your output.