Search code examples
javaconstructorinstance-variables

Initialization of class variables in constructor in java


we know that...

Instance Variable are initialized in default constructor. For eg.

public class H{
    int x;

    public static void main(String... args){
        System.out.print(new H().x);
    }
}

The O/P of above code is 0 because there is a default constructor which is called , and that constructor initialized the x to 0.

Now, my question is, if we run the below code, i.e.

public class H{
        int x;

        public H(){}

        public static void main(String... args){
            System.out.print(new H().x);
        }
}

The actual O/P is 0 in this case also, but I think there should be compiler error that x is not initialized, because we have override the default constructor and didn't initialize x.I think I have made my question clear..


Solution

  • In Java, instance members are defaulted to the all-bits-off version of their value automatically (ints are 0, object references are null, floats are 0.0, booleans are false, and so on). It's not something the default constructor does, it's done before the constructor runs.

    The order is:

    1. Default the instance members to their all-bits-off value. (The optimizer can skip this if it sees #2 below or possibly if it can prove to itself that nothing uses the member prior to an initialization per #3 below.)

    2. Apply any inline initialization of them. For instance:

      int a = 42;
      
    3. Apply instance initialization blocks in source code order.

    4. Call the appropriate constructor.

    So for example:

    class Example {
    
        int a = 42;
    
        // Instance initializer block:
        {
            this.a = 67;
        }
    
        Example() {
            System.out.println(this.a);
        }
    }
    

    new Example() outputs 67.

    Obviously, initializing in both places like that would be poor practice, this is just for illustration.