When Java evaluates a conjunction ( && ), does it eval exp2 if exp1 is false?

前端 未结 5 654
谎友^
谎友^ 2020-12-07 04:08

I\'m wondering if it\'s guaranteed that in a Java program, the boolean expression on the right of a conjunction (exp2 above) will NOT be evaluated as long as the expression

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 04:43

    Let us perform our own experiment by looking directly at the opcodes that are generated from this sample code:

    public class Compare {
    
            public static void main(String... args) {
              boolean t = true;
              boolean f = false;
              if(f && t) {
                System.out.println("Both true");
              }
              else {
                System.out.println("One false");
              }
            }
    
    }
    

    javap -v generates:

       0:   iconst_1
       1:   istore_1
       2:   iconst_0
       3:   istore_2
       4:   iload_2
       5:   ifeq    23
       8:   iload_1
       9:   ifeq    23
       12:  getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
       15:  ldc #3; //String No
       17:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
       20:  goto    31
       23:  getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
       26:  ldc #5; //String Yes
       28:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
       31:  return
    

    The relevant opcodes are ifeq for my small program. They check to see if the variables are equal to 0, and jump a certain number of operations forward if they are, in this case, to opcode 23. So if the first ifeq evaluates to false it will jump past the second ifeq instruction straight to the else statement.

    This is called short circuit evaluation.

提交回复
热议问题