Variable default value in Java

From the reference:

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.


From the Java Language Specification, Java SE 8 Edition, 4.12.5 Initial Values of Variables:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).


Local variables don't get initialized.

This is a local variable:

void aaa() {
    int x;
}

This is an instance variable. These do get initialized automatically:

class X {
    int x;
}

Tags:

Java

Variables