我正在尝试理解 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/