I'm trying to understand java byte code. I started with simple example:
public class Test
{
    public static void main(String args[])
    {
        System.out.println(2 + 1);
    }
}
I compiled this class:
javac Test.java
And then I tried to a javap on the .class like this:
javap -c Test
which gave me this:
Compiled from "Test.java"
public class Test {
  public Test();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        
  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: iconst_1      
       4: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
       7: return        
}
I could able to make sense out of it, apart from this line:
public static void main(java.lang.String[]);
. . . 
3: iconst_1    
. . .
looking at my source and this byte code, looks like javac already done the operation of addition for this statement:
2+1
and asking jvm to return that constant.
Can some one correct me if my understanding is wrong? Does javac performs the operation on compilation for +,-,* etc before it actually runs on the jvm? If so how?
2 + 1 is a compile-time constant expression. The compiler itself replaces it by 3 in the byte-code.
See the Java Language Specification, which says:
Some expressions have a value that can be determined at compile time. These are constant expressions.
See this other chapter for what constitutes a constant expression
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- Literals of primitive type and literals of type String [...]
 - The additive operators + and - [...]
 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With