What will be the result of compiling and running the following program?.
public class Main { public static void main(String[] args) { Main obj = new Main(n); }//from w w w . j a v a2s.c o m static int i = 5; static int n; int j = 7; int k; public Main(int m) { System.out.println(i + ", " + j + ", " + k + ", " + n + ", " + m); } { j = 70; n = 20; } // Instance Initializer Block static { i = 50; } // Static Initializer Block }
Select the one correct answer.
(c)
The program will compile, and print 50, 70, 0, 20, 0, when run.
All fields are given default values unless they are explicitly initialized.
Field i is assigned the value 50 in the static initializer block that is executed when the class is initialized.
This assignment will override the explicit initialization of field i in its declaration statement.
When the main()
method is executed, the static field i is 50 and the static field n is 0.
When an instance of the class is created using the new operator, the value of static field n (i.e., 0) is passed to the constructor.
Before the body of the constructor is executed, the instance initializer block is executed, which assigns the values 70 and 20 to the fields j and n, respectively.
When the body of the constructor is executed, the fields i, j, k, and n, and the parameter m, have the values 50, 70, 0, 20, and 0, respectively.