Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the Java compiler precalculate sums of literals?

int i = 10 + 20;

Is it true that the compiler will process this code, adding 10 + 20, and the byte code is the same as for this line of code?

int i = 30;

Where can I read about it?

like image 803
user471011 Avatar asked Nov 30 '22 17:11

user471011


1 Answers

Yes, and you can even verify it for yourself. Take a small Java file, for example:

public class Main {
  public Main() {
    int i = 10 + 20;
  }
}

Compile it with javac Main.java, and then run javap -c Main to disassemble it:

Compiled from "Main.java"
public class Main extends java.lang.Object{
public Main();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   bipush  30
   6:   istore_1
   7:   return

}

Clearly in the bytecode, you can see the compiler's optimization: bipush 30!

like image 92
ide Avatar answered Dec 05 '22 02:12

ide