public static void main(String[] args) {
String s1 = null;
String s2;
s1.trim(); //No compile error. But run time error
s2.trim(); //compile error.
}
在上面的代码中,s1
初始化后没有赋值
编译器知道 s1
是 null
。那为什么不像s2
那样显示s1.trim()
的编译错误呢?
最佳答案
因为s2
没有初始化,而s1
初始化为null
对于队列 1:您实际上是在 null
上执行 trim()
操作,因此它会抛出 NPE (NullPointerException
) 应该是这样的。
对于问题 2: 参见 §4.12.5 JLS 的详细解释:
A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified by the compiler using the rules for definite assignment.
关于java - 为什么类型的空变量声明显示编译错误而不是空声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18016950/