Why does javac generate different byte codes for two seemingly very similar constructs?

Consider a very simple contrived code example:

 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       

      

  • Why does the compiler generate different byte codes for very similar fields a

    and b

    . Both are integral types, initialized with constant literals.

    For, a

    it fetches a constant from the pool via iconst_3

    and then stores it in a variable via istore_1

    , whereas for b it uses a completely different mechanism (combination of bipush

    and istore

    ).

+3


source to share


1 answer


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

      

Integer -1

- 5

iconst_x

(x is a number from 0 to 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    030 load the int value 0 onto the stack
iconst_1    041 load the int value 1 onto the stack
iconst_2    052 load the int value 2 onto the stack
iconst_3    063 load the int value 3 onto the stack
iconst_4    074 load the int value 4 onto the stack
iconst_5    085 load the int value 5 onto the stack

      



Hence, if the number is not a constant iconst_

bytecode value , then it will use the bytecode bipush

.

More info on java bytecode list && & && JVMS

+7


source







All Articles