Different behaviour of java bytecode

試著忘記壹切 提交于 2019-11-29 06:14:42

问题


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.


回答1:


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.




回答2:


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




回答3:


there is no iconst_9 instruction




回答4:


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




回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/11811774/different-behaviour-of-java-bytecode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!