0 votes
in JAVA by
What should be the execution order, if a class has a method, static block, instance block, and constructor, as shown below?

public class First_C {  

      public void myMethod()   

    {  

    System.out.println("Method");  

    }  

      

    {  

    System.out.println(" Instance Block");  

    }  

          

    public void First_C()  

    {  

    System.out.println("Constructor ");  

    }  

    static {  

        System.out.println("static block");  

    }  

    public static void main(String[] args) {  

    First_C c = new First_C();  

    c.First_C();  

    c.myMethod();  

  }  

}   

i) Instance block, method, static block, and constructor

ii) Method, constructor, instance block, and static block

iii) Static block, method, instance block, and constructor

iv) Static block, instance block, constructor, and method

1 Answer

0 votes
by
iv) Static block, instance block, constructor, and method

Explanation: The order of execution is:

The static block will execute whenever the class is loaded by JVM.

Instance block will execute whenever an object is created, and they are invoked before the constructors. For example, if there are two objects, the instance block will execute two times for each object.

The constructor will execute after the instance block, and it also execute every time the object is created.

A method is always executed at the end.

Related questions

0 votes
asked Apr 9, 2021 in JAVA by Robindeniel
0 votes
asked Apr 8, 2021 in JAVA by SakshiSharma
...