鉴于此 Java 代码:
int fst = 5;
int snd = 6;
if(fst == snd)
do something;
我想知道 Java 将如何比较这种情况下的相等性。它会使用 XOR 操作来检查相等性吗?
鉴于此 Java 代码:
int fst = 5;
int snd = 6;
if(fst == snd)
do something;
我想知道 Java 将如何比较这种情况下的相等性。它会使用 XOR 操作来检查相等性吗?
如果您询问 JVM,请使用该javap
程序。
public class A {
public static void main(String[] args) {
int a = 5;
System.out.println(5 == a);
}
}
下面是拆解:
public class A {
public A();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
2: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
5: iconst_5
6: iload_1
7: if_icmpne 14
10: iconst_1
11: goto 15
14: iconst_0
15: invokevirtual #3 // Method java/io/PrintStream.println:(Z)V
18: return
}
在这种情况下,它稍微优化了分支并使用了if_icmpne
. 在大多数情况下,它将使用if_icmpne
or if_icmpeq
。
if_icmpeq
:if ints are equal, branch to instruction at branchoffset (signed short constructed from unsigned bytes branchbyte1 << 8 + branchbyte2)
if_icmpn
:if ints are not equal, branch to instruction at branchoffset (signed short constructed from unsigned bytes branchbyte1 << 8 + branchbyte2)