java - 为什么 javac 提示没有初始化变量?

标签 java initialization

对于这段 Java 代码:

String var;
clazz.doSomething(var);

编译器为什么会报这个错:

Variable 'var' might not have been initialized

我以为所有的变量或引用都被初始化为null。为什么需要这样做:

String var = null;

??

最佳答案

实例和类变量被初始化为 null(或 0),但局部变量不是。

参见 §4.12.5JLS一个非常详细的解释,基本上说的是同一件事:

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/

相关文章:

c - 堆栈上的结构 - 字段已初始化?

c++ - 静态数据成员作为 C++ 默认参数是否安全?

C++ 类实例未初始化但没有编译错误,为什么

java - 避免已存在的更新验证并在 Spring MVC 中进行更新

python - 在Python中的对象初始化中将self传递给函数

java.util.Date.parse() 解析 Wed Apr 03 00 :00:00 BST 2013 时抛出异常

java - 为什么我的int[][]填充的是1而不是0?

c - 如何使用 C 语言中的预编译器初始化数组

java - rxjava : Can I use retry() but with delay?

java - 添加 jar 作为 Play 项目的依赖项时,IntelliJ 找不到 OpenCV 的 native 库