问题描述
我从>编译时常量和变量。
- 声明为最终
- 具有基本类型或字符串类型
- 与声明同时初始化
- 用常量表达式初始化
- declared as final
- have a primitive or String type
- initialized at the same time as the declaration
- initialized with constant expression
final int x = 5;
但是我不明白为什么下面的代码没有:
But I fail to understand why below code doesn't:
final int x;
x = 5;
唯一的区别是上面的第三点。
不同行而不是同一行的初始化有何不同。
The only difference is of third point above.How initialization on different line instead of same line makes a difference.
推荐答案
案例1 final int x = 5;
public static void main(String[] args) {
final int x = 5;
}
生成的字节码为:
public static main([Ljava/lang/String;)V
L0
LINENUMBER 3 L0
ICONST_5
ISTORE 1
L1
LINENUMBER 4 L1
RETURN
L2
LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
LOCALVARIABLE x I L1 L2 1
MAXSTACK = 1
MAXLOCALS = 2
案例2 final int x; x = 5;
public static void main(String[] args) {
final int x;
x = 5;
}
生成的字节码为:
public static main([Ljava/lang/String;)V
L0
LINENUMBER 4 L0
ICONST_5
ISTORE 1
L1
LINENUMBER 5 L1
RETURN
L2
LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
LOCALVARIABLE x I L1 L2 1
MAXSTACK = 1
MAXLOCALS = 2
如您所见,这两种情况之间没有区别,除了行号。
实际上,在诸如InteliJ之类的想法中,您会看到提示(作为灯泡),将情况2的2行连接到情况1的1行。 >
如果您阅读了提供的链接中的所有答案和评论,则
会让您感到困惑而不是明智。
全部与术语有关,在这种情况下,未记录术语。
这是该链接中答案的一部分:
As you can see there is no difference between the 2 cases, except for the line numbers.
In fact in an ide such as InteliJ you will see the prompt (as a light bulb) to join the 2 lines of case 2, to 1 line like case 1.
If you read all the answers and comments in the link you provided,
you will be more confused than wiser about this.
It's all about terminology and in this case not documented terminology.
This is an excerpt of one of the answers in that link:
现在说明编译器如何使用这两种情况。
如果在这两种方法的末尾都添加了这一行:
Now for the case of how the compiler uses the 2 cases.
If you add this line at the end of both methods:
System.out.println(x);
生成的字节码为:
对于情况1
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ICONST_5
INVOKEVIRTUAL java/io/PrintStream.println (I)V
对于第2种情况
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ILOAD 1
INVOKEVIRTUAL java/io/PrintStream.println (I)V
第二种情况有所不同: ILOAD 1
而不是 ICONST_5
。
意思是在第一种情况下 x
被替换为5,而在第二种情况下没有,而 x
的值被调用(加载)执行该语句。
There is a difference in the 2nd case: ILOAD 1
instead of ICONST_5
.
Meaning in the 1st case x
was replaced by 5 and in the 2nd case it was not and the value of x
was recalled (loaded) to execute the statement.
这篇关于编译时间常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!