有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

初始化Java中声明的、未初始化的变量会发生什么情况?

它有价值吗

我试图理解Java中已声明但未初始化的变量/对象的状态

我无法实际测试它,因为我不断得到“未初始化”编译错误,似乎无法抑制它

例如,如果变量是一个integer,那么它可能等于0

但是如果变量是一个字符串,它将等于null还是isEmpty()将返回true

所有未初始化变量的值是否相同?或者每个声明(含义、int、字符串、double等)在未显式初始化时都有不同的值


更新

因此,正如我现在看到的,如果变量被声明为locally或在Class中,这会产生很大的不同,尽管我似乎无法理解为什么在类中声明为静态时不会出现错误,但在主中声明时会产生"Not Initialized" error


共 (3) 个答案

  1. # 1 楼答案

    Fabian已经提供了一个非常明确的答案,我只是尝试添加来自official documentation的规范以供参考

    类中的字段

    It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

    如果没有指定default value,它只能被视为坏的样式,而local variables中的情况不同

    局部变量

    Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

  2. # 2 楼答案

    JVM如何做到这一点完全取决于JVM,对于程序员来说并不重要,因为编译器确保您不会读取未初始化的局部变量

    然而,字段是不同的。在读取它们之前,不需要分配它们(除非它们是final),对于引用类型,未分配的字段的值是null,如果字段具有基元类型,则相应基元类型的0

    对未分配的String s;字段使用s.isEmpty()会导致NullPointerException


    So as I see now, it makes a big difference if the variable is declared locally or in the Class, though I seem to be unable to understand why when declaring in the class it gives no error, but when declaring in the main it produces the "Not Initialized" error.

    一般来说,使用没有价值的值是不可取的。因此,语言设计师有两种选择:

    a)为尚未初始化的变量定义默认值
    b) 防止程序员在写入变量之前访问变量

    b)对于油田而言很难实现,因此选择了选项a)作为油田。(根据调用顺序,可能有多个读/写方法有效或无效,这只能在运行时确定)

    对于局部变量,选项b)是可行的,因为可以检查方法执行的所有可能路径是否有赋值语句。这个选项是在局部变量的语言设计过程中选择的,因为它可以帮助发现许多容易犯的错误