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?
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?
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.
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 :
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
!