Default Values and Initialization in Java

Michael 'Maik' Ardan picture Michael 'Maik' Ardan · Oct 2, 2013 · Viewed 151.1k times · Source

Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.

public class Main {
    public static void main(String[] args) {
        int a;
        System.out.println(a);
    }
}

The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.

public class Main {
    static int a;
    public static void main(String[] args) {
        System.out.println(a);
    }
}

What could possibly go wrong with the first code? Does class instance variable behaves different from local variables?

Answer

Juned Ahsan picture Juned Ahsan · Oct 2, 2013

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to default value .