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
andb
. Both are integral types, initialized with constant literals.For,
a
it fetches a constant from the pool viaiconst_3
and then stores it in a variable viaistore_1
, whereas for b it uses a completely different mechanism (combination ofbipush
andistore
).
source to share
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 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 iconst_
bytecode value , then it will use the bytecode bipush
.
More info on java bytecode list && & && JVMS
source to share