Predict the output of following Java Programs:
The program works fine and prints 10. In Java, members can initialized with declaration of class. This initialization works well when the initialization value is available and the initialization can be put on one line (See this for more details). For example, the following program also works fine.
Output of the above program is “x = 4, y = 2”. y is initialized first, then x is initialized as y + 2. So the value of x becomes 4.
What happen when a member is initialized in class declaration and constructor both? Consider the following program.
Output of the above program is “x = 5”. The initialization with class declaration in Java is like initialization using Initializer List in C++. So, in the above program, the value assigned inside the constructor overwrites the previous value of x which is 2, and x becomes 5.
As an exercise, predict the output of following program.
The output of the program is Constructor called 10 Constructor called 5.
First t2 object is instantiated in the main method. As the order of initialization of local variables comes first than the constructor,first the instance variable (t1), in the class Test2 is allocated to the memory. In this line a new Test1 object is created, constructor is called in class Test1 and ‘Constructor called 10’ is printed. Next the constructor of Test2 is called and again a new object of the class Test1 is created and ‘Constructor called 5’ is printed.
Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.