Question

May be this is a stupid question? Sorry it sounds so. I have following codes.

Condition 1

public class Test {

    int a;

    void display() {
        System.out.println(a);
    }
}

Condition 2

public class Test {

    void display() {
        int a;
        System.out.println(a);
    }
}

I am very clear about the second condition. The a is not initialized. So, this will produce an error. But in first condition, I've not initialized property a. While running the following code, it will not produce an error. Instead it will display 0. It may be due to integer is initialized to 0.

Test t;
t = new Test();
t.display();

What is the logic behind not to initialize local variable and to initialize property(integer) to 0?

Was it helpful?

Solution

See Java Language Specification section 4.12.5: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5

"Each class variable, instance variable, or array component is initialized with a default value when it is created.

"A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified using the rules for definite assignment."

OTHER TIPS

int is a primitive type and must be initialized, so java does it for you.

Change int to Integer and you will get a null pointer exception.

If you create an Object in the same fashion, that is without initialization, you have just created a reference = to null on the stack. There is not actually an Object on the heap until you initialize one with a constructor. When you initialize an Object, its class values are initialized as well. That way any user of the Object can access or mutate the values.

There is one BIG exception, Local Variables. Because local variables are usually used for immediate calculations, java does not initialize them. If you forget to do so, java will throw a compiler error to prevent you from make a calculation using a default value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top