对于这段 Java 代码:
String var;
clazz.doSomething(var);
编译器为什么会报这个错:
Variable 'var' might not have been initialized
我以为所有的变量或引用都被初始化为null
。为什么需要这样做:
String var = null;
??
最佳答案
实例和类变量被初始化为 null(或 0),但局部变量不是。
参见 §4.12.5的 JLS一个非常详细的解释,基本上说的是同一件事:
Every variable in a program must have a value before its value is used:
- Each class variable, instance variable, or array component is initialized with a default value when it is created:
- [snipped out list of all default values]
- Each method parameter is initialized to the corresponding argument value provided by the invoker of the method.
- Each constructor parameter is initialized to the corresponding argument value provided by a class instance creation expression or explicit constructor invocation.
- An exception-handler parameter is initialized to the thrown object representing the exception.
- 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 - 为什么 javac 提示没有初始化变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2187632/