Output of Java Program | Set 3
Predict the output of the following Java Programs:
In Java, members can be initialized with the declaration of the 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).
x = 4, y = 2
A pretty straightforward solution: As y is initialized first with the value 2, then x is initialized as y + 2. So the value of x becomes 4.
Geek have you ever wondered what will happen when a member is initialized in class declaration and constructor both?
x = 5
The initialization with the 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.
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 then 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, the 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.