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

前端 未结 5 1806
自闭症患者
自闭症患者 2020-11-27 06:25
public class Foo {
    public static void main(String[] args) {
        float f;
        System.out.println(f);
    }
}

The print statement causes

5条回答
  •  被撕碎了的回忆
    2020-11-27 06:56

    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.

提交回复
热议问题