Java ByteCode arithmetic operation

守給你的承諾、 提交于 2021-01-29 18:19:54

问题


I'm going to make a simple compiler for a school project, i want generate .class file, i read the file format but to understand better the .class file format and the java bytecode i have this class:

public class Me {
    public void myMethod() {
        int a = 5 * 4 + 3 - 2 + 1 / 7 + 28;
    }
}

with javap command i get this(for 'myMethod'):

public void myMethod();
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=1
         0: bipush        49
         2: istore_1      
         3: return        
      LineNumberTable:
        line 3: 0
        line 4: 3
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       4     0  this   LMe;
               3       1     1     a   I

In this line:

 0: bipush        49

I dont understand when we get that number(49), i dont see the byte code for the arithmetic operation '5 * 4 + 3 ...'


回答1:


I dont understand when we get that number(49), i dont see the byte code for the arithmetic operation '5 * 4 + 3

The bytecode compiler is optimizing them away. The expression is a constant expression according to the JLS definition, and that means that the java compiler is permitted to evaluate it at compile time and hard-code the resulting value into the class file.

If you want to see what the bytecodes for expression evaluation look like, you need to use parameters, local variables, etc as the "primaries" in the expression; e.g.

public int myMethod(int a, int b, int c) {
    return a + b * c / 42;
}


来源:https://stackoverflow.com/questions/23976406/java-bytecode-arithmetic-operation

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