views:

109

answers:

3
int i=10+20;

It is true that the compiler will process this code, it adds 10 +20, and the byte code is the same as for this line of code:

int i=30;

?

and where can I read about it?

+4  A: 

Yes. This compiler optimization is called constant folding. There's another compiler optimization called sparse conditional constant propagation that does something similar.

In general, there's no guarantee that a given compiler will actually fold constants, but nowadays just about every compiler for every language does this. In particular, the Java Language Specification requires that constant expressions be evaluated at compile time.

In silico
+1  A: 

Yes, it will be simplified as required by the JLS (thanks to @EJP for this precision).

If you want more resources and javac optimization you should take a look at Compiler optimizations or Java Compilers.

Another interesting thing is that even if your code is optimized during the compilation, a second optimization will be done during runtime with hotspot.


Resources :

On the same topic :

Colin Hebert
You can rely on the Java compiler evaluating constant expressions. It is required by the specification, so that for example case labels that are CEs can be legal.
EJP
@EJP, I'm not 100% sure about that so I'll change my answer, but can you provide a link to the specification on this particular optimization?
Colin Hebert
The fact that CEs are allowed in case expressions makes it compulsory. See 15.28 Constant Expressions.
EJP
@EJP, thanks I just found it, I'll adapt my answer.
Colin Hebert
EJP, if you had written this as answer, you'd have gotten at least one upvote ;-)
meriton
+7  A: 

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!

ide