Open In App

Java | Constructors | Question 8

Like Article
Like
Save
Share
Report




class Test
{
    static int a;
      
    static
    {
        a = 4;
        System.out.println ("inside static block\n");
        System.out.println ("a = " + a);
    }
      
    Test()
    {
        System.out.println ("\ninside constructor\n");
        a = 10;
    }
      
    public static void func()
    {
        a = a + 1;
        System.out.println ("a = " + a);
    }
      
    public static void main(String[] args)
    {
  
        Test obj = new Test();
        obj.func();
  
    }
}
  


(A)

inside static block
a = 4
inside constructor
a = 11

(B) Compiler Error
(C) Run Time Error
(D)

inside static block
a = 4
inside constructor
a = 5

(E)

inside static block
a = 10
inside constructor
a = 11


Answer: (A)

Explanation: Static blocks are called before constructors. Therefore, on object creation of class Test, static block is called. So, static variable a = 4.
Then constructor Test() is called which assigns a = 10. Finally, function func() increments its value.

Quiz of this Question
Please comment below if you find anything wrong in the above post


Last Updated : 28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads