16

I am a newbee in Java Bytecode. I was understanding the bytecode through some examples but I got stuck in an example.
These are my java and bytecode file

class SimpleAdd{
    public static void main(char args[]){
        int a,b,c,d;
        a = 9;
        b = 4;
        c = 3;
        d = a + b + c;
        System.out.println(d);
    }
}  
Compiled from "SimpleAdd.java"
class SimpleAdd extends java.lang.Object{
SimpleAdd();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(char[]);
  Code:
   0:   bipush  9
   2:   istore_1
   3:   iconst_4
   4:   istore_2
   5:   iconst_3
   6:   istore_3
   7:   iload_1
   8:   iload_2
   9:   iadd
   10:  iload_3
   11:  iadd
   12:  istore  4
   14:  getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   17:  iload   4
   19:  invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   22:  return

}  

I just want to know why there is bipush 9 when we have instruction a = 9
And in all other case there is iconst.

neel
  • 8,399
  • 7
  • 36
  • 50
  • 3
    `bipush 9` pushes the integer literal 9 onto the stack. `istore_1` stores that value into local variable #1. `iconst_4` pushes a literal 4 onto the stack, and does it in one byte vs two for the `bipush`, but there are only the `iconst_1` through `iconst_5` bytecodes -- no `iconst_9`. – Hot Licks Aug 04 '12 at 20:31

6 Answers6

25

iconst can push constant values -1 to 5. It is a single-byte instruction.

bipush can push constant values between -128 and 127. It is a two-byte instruction.

To push 9 you cannot use iconst. There is no iconst_9 instruction.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

iconst_n is defined for n from 0 to 5

There's no iconst_9, so you have to use the equivalent (but less efficent) bipush

Austin Schmidt
  • 316
  • 1
  • 13
Haile
  • 3,120
  • 3
  • 24
  • 40
  • 1
    `iconst` supports values [from minus one to five](http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.iconst_i)… – Holger Aug 18 '15 at 15:33
0

there is no iconst_9 instruction

ddyer
  • 1,792
  • 19
  • 26
0

the i_const instruction only range from 0~5, so it must spit the instuction by push and store

mannnnerd
  • 109
  • 1
  • 4
0

The instructions iconst_* are optimised to work with small and specific numbers while bipush (push a byte onto the stack as an integer value) works for bigger numbers.

0

There is no iconst_9 instruction. So to push 9 you cannot use iconst. You must go for bipush

Ratnesh
  • 298
  • 3
  • 14