在 Java 中,有什么区别和最好的方法?
Integer x = null; // x later assign some value.
Integer y; // y later initialize and use it.
最佳答案
答案取决于您指的是什么类型的变量。
对于类变量,没有区别,参见JLS - 4.12.5. Initial Values of Variables :
... Every variable in a program must have a value before its value is used:
For all reference types (§4.3), the default value is
null
.
意思是,没有区别,后者隐式设置为null
。
如果变量是本地,则必须在将它们传递给方法之前对其进行赋值:
myMethod(x); //will compile :)
myMethod(y) //won't compile :(
关于java - 局部变量初始化 null 和不初始化之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26160236/