Search code examples
javabytecode.class-file

Java ByteCode arithmetic operation


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 ...'


Solution

  • 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;
    }