Take the 2-minute tour ×
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?

share|improve this question

3 Answers 3

up vote 9 down vote accepted

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();
   0:   aload_0
   4:   bipush  30
   6:   istore_1
   7:   return


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

share|improve this answer

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.

share|improve this answer

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 :

share|improve this answer
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 Oct 9 '10 at 23:13
@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 Oct 9 '10 at 23:15
The fact that CEs are allowed in case expressions makes it compulsory. See 15.28 Constant Expressions. –  EJP Oct 9 '10 at 23:27
@EJP, thanks I just found it, I'll adapt my answer. –  Colin Hebert Oct 9 '10 at 23:29
EJP, if you had written this as answer, you'd have gotten at least one upvote ;-) –  meriton Oct 9 '10 at 23:51

Your Answer


