korujzade korujzade - 4 months ago 11
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
bar
in the output.

Answer

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.