Predict the output of the following Java Programs:
Example1:
Java
class Test {
int x = 10 ;
public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.x);
}
}
|
Output explanation:
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).
Example 2:
Java
class Test {
int y = 2 ;
int x = y + 2 ;
public static void main(String[] args)
{
Test m = new Test();
System.out.println( "x = " + m.x + ", y = " + m.y);
}
}
|
Output explanation:
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?
Example 3:
Java
public class Test {
int x = 2 ;
Test( int i) { x = i; }
public static void main(String[] args)
{
Test t = new Test( 5 );
System.out.println( "x = " + t.x);
}
}
|
Output explanation:
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.
Example 4:
Java
class Test1 {
Test1( int x)
{
System.out.println( "Constructor called " + x);
}
}
class Test2 {
Test1 t1 = new Test1( 10 );
Test2( int i) { t1 = new Test1(i); }
public static void main(String[] args)
{
Test2 t2 = new Test2( 5 );
}
}
|
OutputConstructor called 10
Constructor called 5
Output explanation:
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.