Java: Why am I required to initialize a primitive local variable?

孤人 提交于 2019-11-26 08:25:41

问题


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

The print statement causes the following compile-time error,

The local variable f may not have been initialized

If primitives in Java already have a default value (float = 0.0f), why am I required to define one?


Edit:

So, this works

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

Thanks, everyone!


回答1:


Because it's a local variable. This is why nothing is assigned to it :

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.

Edit: Why does Java raise this compilation error ? If we look at the IdentifierExpression.java class file, we will find this 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++;
        }
...

As stated (if (!vset.testVar(local.number)) {), the JDK checks (with testVar) if the variable is assigned (Vset's source code where we can find testVar code). If not, it raises the error var.not.initialized from a properties file :

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

Source




回答2:


In fact, the compiler does not assign a default value to your float f, because in this case it is a local variable -- and not a field:

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.




回答3:


Class fields (non-final ones anyway) are initialized to default values. Local variables are not.

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.

So a (non-final) field like f in

class C {
  float f;
}

will be initialized to 0f but the local variable f in

void myMethod() {
  float f;
}

will not be.

Local variables are treated differently from fields by the language. Local variables have a well-scoped lifetime, so any use before initialization is probably an error. Fields do not so the default initialization is often convenient.




回答4:


Actually local variables are stored in stack.Hence there is a chance of taking any old value present for the local variable.It is a big challenge for security reason..Hence java says you have to initialise a local varible before use.




回答5:


Hi guys solution is simple. the values that are stored on the heap memory are initialized by the compiler based datatype but local variables are stored on stack memory so we have to inialize it explictly.



来源:https://stackoverflow.com/questions/11165485/java-why-am-i-required-to-initialize-a-primitive-local-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!