Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the binary operators execution happen in Java?

Tags:

java

jvm

bytecode

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?

like image 644
batman Avatar asked Aug 16 '15 11:08

batman


1 Answers

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 - [...]
like image 153
JB Nizet Avatar answered Oct 24 '22 07:10

JB Nizet