Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If we define own constructor then how does java initialize instance variables to their default value

Java assigns default values to instance variables using default constructor. But if we define our own constructor then how does java give default values (because when we write our constructor then, then default constructor is not added).

like image 981
swdeveloper Avatar asked Jun 11 '12 09:06

swdeveloper


1 Answers

Java assigns default values to instance variables using default constructor.

No, not really. It automatically assigns default values to all members prior to executing any constructor.

But if we define our own constructor then how does java give default values (because when we write our constructor then, then default constructor is not added).

It still assigns default values to all members.

class Test {

    int i;
    Object ref;

    Test() {
        System.out.println(i);
        System.out.println(ref);
    }


    public static void main(String[] args) {
        new Test();
    }
}

Output:

0
null
like image 98
aioobe Avatar answered Oct 18 '22 09:10

aioobe