以下代码在执行时打印 nitesh null
而不是预期的 nitesh 130
。
为什么 n
在执行静态 block 之前没有初始化?
class test
{
static
{
System.out.println(test.str+" "+test.n);
}
final static String str="nitesh";
final static Float n=130f;
public static void main(String []args)
{
}
}
最佳答案
str
是编译时常量 - n
不是,因为它是 Float
类型。如果将其更改为 final static float n = 130f
,那么您将在静态初始化 block 中看到该值。
所以目前,在静态初始化 block 中,str
的值实际上被内联了——你的代码相当于:
System.out.println("nitesh "+test.n);
来自 JLS section 15.28 (constant expressions) :
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: [...]
Float
不是原始类型。
此外,即使没有内联,常量变量 str
也会在任何静态初始化程序 block 执行之前被初始化。来自 section 12.4.2 of the JLS (类初始化细节):
- ...
- Then, initialize the static fields of C which are constant variables (§4.12.4, §8.3.2, §9.3.1).
- ...
- Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
关于java - 为什么在执行静态 block 时这个Float常量为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24202941/