Java:为什么我需要初始化一个原始局部变量?

标签 java primitive

public class Foo {
    public static void main(String[] args) {
        float f;
        System.out.println(f);
    }
}

打印语句导致以下编译时错误,

The local variable f may not have been initialized

如果 Java 中的原语已经有 default value (float = 0.0f) ,为什么要我定义一个?


编辑:

所以,这行得通

public class Foo {
    float f;
    public static void main(String[] args) {
        System.out.println(new Foo().f);
    }
}

谢谢大家!

最佳答案

因为它是一个局部变量。这就是为什么没有分配给它的原因:

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.

编辑:为什么 Java 会引发此编译错误? 如果我们查看 IdentifierExpression.java 类文件,我们会发现这个 block :

...
if (field.isLocal()) {
            LocalMember local = (LocalMember)field;
            if (local.scopeNumber < ctx.frameNumber && !local.isFinal()) {
                env.error(where, "invalid.uplevel", id);
            }
            if (!vset.testVar(local.number)) {
                env.error(where, "var.not.initialized", id);
                vset.addVar(local.number);
            }
            local.readcount++;
        }
...

如前所述 (if (!vset.testVar(local.number)) {),JDK 检查 (使用 testVar) 变量是否已分配 ( Vset's source code 其中我们可以找到 testVar 代码)。如果不是,它会从 properties file 引发错误 var.not.initialized :

...
javac.err.var.not.initialized=\
    Variable {0} may not have been initialized.
...

Source

关于Java:为什么我需要初始化一个原始局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11165485/

相关文章:

java - Jsch 文件上传已取消

java - 从jar中读取资源文件

java - java获取系统帐户信息?

Java:整数等于 vs. ==

java - 将原始 int 转换为 Number

java - 为什么此方法重载模棱两可?

java - OpenJPA 脏读提示

java - 将 Hashmap 用于键的多个值,为什么?

java - 关于原语的快速问题

java - int 的可变长度编码为 2 个字节