Hope this can clarify your question. Why spend 4 Opcode.
See the byte code of this code.
public static void main(String[] args) { int b = 20; int c = 5; int d= 6; }
part of byte code
0: bipush 20 2: istore_1 3: iconst_5 4: istore_2 5: bipush 6 7: istore_3
As you can see for numbers greater than 5, it starts using bipush , which are usually less efficient than the equivalent iconst_<n> , and also occupy more bytes in the class file.
bipush byte1 extends byte1 to int and then pushes it onto the stack, because each slot in the Java stack is 32 bits wide (JVMs are stack-based virtual machines)
And to make sure bipush takes up more bytes ..
See the class file size from the following two codes. (This size is on my 64-bit computer .. it may differ on your computer, but the difference will be the same)
public class Test2 { public static void main(String[] args) { int b = 5; } }
size 406 bytes
now if i replaced b =6 ; the size of the same class file becomes 407 bytes , which remains constant as long as b=127 , which also uses bipush . This size difference is due to the fact that bipush has 2 bytes, one byte operation code, the second byte instantaneous constant value
bipush format:
bipush byte
as you can see from line 5: bipush 6 in the bytecode, while iconst_<n> uses only 1 byte.
Thus, such byte codes are defined for some frequently advanced numbers in order to increase the efficiency of the byte code execution and reduce the size of the byte code streams.
and, as Tagir said, these numbers will be used more often than you think.