Search code examples
javabranchbytecode.class-fileconditional-statements

Java conditionals in class-file (on bytecode level)


I'm playing a bit with Java class files and bytecode. But I stuck at the conditions in the class file. In theory, I understand the concept, but I don't understand how the branching in the classfile is done. Here is a small example:

public static void main(String[] args) {
  int a = 78;
  int b = 52;
  boolean c;

  if(a==b){
    c = true;
  } else {
    c = false;
  }
}

Using javap -c -verbose Equal.class the following listing came up:

flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=4, args_size=1
         0: bipush        78
         2: istore_1      
         3: bipush        52
         5: istore_2      
         6: iload_1       
         7: iload_2       
         8: if_icmpne     16
        11: iconst_1      
        12: istore_3      
        13: goto          18
        16: iconst_0      
        17: istore_3      
        18: return        
      LineNumberTable:
        line 4: 0
        line 5: 3
        line 7: 6
        line 8: 11
        line 10: 16
        line 11: 18
      StackMapTable: number_of_entries = 2
           frame_type = 253 /* append */
             offset_delta = 16
        locals = [ int, int ]
           frame_type = 252 /* append */
             offset_delta = 1
        locals = [ int ]

Now I was looking in the class file, to find the branch. The hex presentation for the opcode if_icmpne is 0xA0. I assumed the branch marker would follow the 0xA0. In my case there are 2 bytes: 0x0008. My question: What does the two bytes (0x0008) represent? I tried a lot. For example I followed the pathes through the LineNumberTable and the Constant Pool but could'n find anything that would make sense.

(Of course the same for goto)

In addition, here is the full sequence for the postet listing above:

10 4E  // bipush 78
3C     // istore_1
10 34  // bipush 52
3D     // istore_2
1B     // iload_1
1C     // iload_2
A0     // if_icmpne
00 08  // ???
04     // iconst_1
3E     // istore_3
A7     // goto
00 05  // ???
03     // iconst_0
3E     // istore_3
B1     // return

Thank you in advance!


Solution

  • The 0x0008 is the branch-offset - that is the number of bytes to jump forward from the current instruction to find the next instruction. So from if_icmpne jump 8 bytes (->00->08->04->3E->A7->00->05->03) to iconst_0. It is the same for the goto: from goto jump 5 bytes (->00->05->03->3E->B1) to return.