Search code examples
javabytecodejavap

Why javac produces different byte code for two seemingly very similar constructs?


Consider the very simple contrived example code :

 public class TestJavap {
    public static void main(String[] args) {
        int a = 3;
        int b = 7;
    }
}

javap produces this :

 public static void main(java.lang.String[]);
  Code:
   0: iconst_3      
   1: istore_1      
   2: bipush        7
   4: istore_2      
   5: return       
  1. Why the compiler is producing different byte code for very similar fields a and b. Both are integral types initialized with constant literals.

    For a it fetches the constant from the pool via iconst_3 and then stores it in the variable via istore_1 whereas for b it uses a completely different mechanism (combination of bipush and istore).


Solution

  • why the compiler is producing different byte code for very similar fields a and b
    

    From integer -1 - 5 iconst_x(x is number ranging from 0 - 5) is used that it is already a constant number bytecode.

    iconst_m1   02      → -1    load the int value -1 onto the stack
    iconst_0    03      → 0 load the int value 0 onto the stack
    iconst_1    04      → 1 load the int value 1 onto the stack
    iconst_2    05      → 2 load the int value 2 onto the stack
    iconst_3    06      → 3 load the int value 3 onto the stack
    iconst_4    07      → 4 load the int value 4 onto the stack
    iconst_5    08      → 5 load the int value 5 onto the stack
    

    Hence if the number is not a constant value of iconst_ bytecode then it will be using the bipush bytecode.

    More info on the list of java bytecode && JVMS