neel
neel

Reputation: 9061

Different behaviour of java bytecode

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.

Upvotes: 17

Views: 2242

Answers (6)

Ratnesh
Ratnesh

Reputation: 318

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

Upvotes: 0

user10180030
user10180030

Reputation:

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.

Upvotes: 0

Haile
Haile

Reputation: 3180

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

Upvotes: 6

Mark Byers
Mark Byers

Reputation: 838116

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.

Upvotes: 26

mannnnerd
mannnnerd

Reputation: 107

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

Upvotes: 0

ddyer
ddyer

Reputation: 1788

there is no iconst_9 instruction

Upvotes: 0

Related Questions