二元运算符何时在 Java 中执行?

When does the binary operators execution happen in Java?

我正在尝试理解 java 字节码。我从简单的例子开始:

public class Test
{
    public static void main(String args[])
    {
        System.out.println(2 + 1);
    }
}

我编译了这个class:

javac Test.java

然后我尝试在 .class 上 javap 像这样:

javap -c Test

这给了我这个:

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        
}

我能理解它,除了这一行:

public static void main(java.lang.String[]);
. . . 
3: iconst_1    
. . .

查看我的源代码和这段字节码,看起来 javac 已经为这条语句完成了加法操作:

2+1

并要求 jvm return 该常量。

如果我的理解有误,能否有人指正? javac在jvm上实际运行之前是否对+-*等进行了编译操作?如果有怎么办?

2 + 1 是一个编译时常量表达式。编译器本身在字节码中将其替换为 3。

查看 Java Language Specification,其中显示:

Some expressions have a value that can be determined at compile time. These are constant expressions.

请参阅 this other chapter 了解什么是常量表达式

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 - [...]