Given this Java code:
int fst = 5;
int snd = 6;
if(fst == snd)
do something;
I want to know how Java will compare equality for this case. Will it use an XOR operation to check equality?
2 Answers 2
Are you asking "what native machine code does this turn into?"? If so, the answer is "implementation-depdendent".
However, if you want to know what JVM bytecode is used, just take a look at the resulting .class file (use e.g. javap to disassemble it).
3 Comments
int equality" up to the writers of JVM, he/she might as well write the JVM for them :)== happens to turn into.In case you are asking about the JVM, use the javap program.
public class A {
public static void main(String[] args) {
int a = 5;
System.out.println(5 == a);
}
}
Here is the disassembly:
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
}
In this case it optimized the branching a bit and used if_icmpne. In most cases, it will use 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)
if_icmpeqJVM bytecode instruction.==operation translates to theif_icmpeqinstruction in bytecode; during execution, this pops off the object references from the operand stack and compares them.if_icmpeqpops the top twointsoff the stack and compares them. If the two integers are equal, execution branches to the address (pc+branchoffset), where pc is the address of theif_icmpeqopcode in the bytecode andbranchoffsetis a 16-bit signed integer parameter following theif_icmpeqopcode in the bytecode. If the integers are not equal, execution continues at the next instruction.