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

标签 java jvm bytecode

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

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

我编译了这个类:

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 返回该常量。

如果我的理解有误,有人可以纠正我吗? 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 - [...]

关于java - 二元运算符何时在 Java 中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034709/

相关文章:

java - Zuul路由: One endpoint with multiple microservices

java - 无法理解为什么 "ajp-nio-8009-exec-XX"线程在 AbstractQueuedSynchronizer$ConditionObject.await 上阻塞/time_wait

java - 乘法/移位优化是否应该在 Java 字节码中可见

java - Java VM EXCEPTION_ACCESS_VIOLATION 的可能原因?

ilasm/ildasm 的 Java 字节码等价物

java - Gradle sourceCompatibility 对子项目没有影响

java - 如何检查Java流是否有序?

java - .Net 客户端 - 使用 tls1.2 的 Java 服务器连接问题

java - 使用 "final static"或 "static final"是否正确?

jvm - 监控 Storm JVM 指标