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

前端 未结 5 1809
自闭症患者
自闭症患者 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:58

    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.

提交回复
热议问题