Java claims unpleasant side effect - compiler error?

it

public class test { public static void main(String[] args) { Object o = null; assert o != null; if(o != null) System.out.println("o != null"); } } 

prints "o! = null"; both 1.5_22 and 1.6_18. Compiler error? Commenting on the statement, he corrects it. By default, the bytecode goes directly to the print statement when statements are disabled:

  public static main(String[]) : void L0 LINENUMBER 5 L0 ACONST_NULL ASTORE 1 L1 LINENUMBER 6 L1 GETSTATIC test.$assertionsDisabled : boolean IFNE L2 ALOAD 1: o IFNONNULL L2 NEW AssertionError DUP INVOKESPECIAL AssertionError.<init>() : void ATHROW L2 LINENUMBER 8 L2 GETSTATIC System.out : PrintStream LDC "o != null" INVOKEVIRTUAL PrintStream.println(String) : void L3 LINENUMBER 9 L3 RETURN L4 
+4
source share
3 answers

I do not know about the "trouble." Can you give a real example of some code where this will bite you? Your example looks very far-fetched.

EDIT - out of curiosity, I typed a program, compiled it, and ran it using java 1.6.0_16. The compiler error is obvious to me:

  • With statements enabled (java -ea test) I get a statement error.
  • With statements disabled (java test) I am not getting output.
+1
source

Claims can be turned on and off at runtime. If you execute your code with -ea-switch (to enable statements), assert should work:

 java -ea my.class 
+1
source

The JVM optimizes the if (o! = Null) clause because you have already argued that o will never be null.

Assertion is not enabled by default at runtime and is usually used to verify that this code is executing a contract, for example. you just want to make sure that a particular object will never be null (for example, to exclude null pointer exceptions). It is because of this β€œcontract” that the compiler can optimize if (o! = Null), because it knows that this condition will never happen.

Since they are generally not included at run time, think of them as help in developing a piece of code, rather than as a mechanism for checking errors at run time.

0
source

Source: https://habr.com/ru/post/1301563/


All Articles