Javatpoint Logo
Javatpoint Logo

Execute the Main Method Multiple Times in Java

In this tutorial, we will see how one can execute the main() method multiple times in Java.

Approach: Using Static Block

We know that the static block is executed first. Therefore, it can be used to execute the main method explicitly. One is executed implicitly as the main method is automatically invoked by the JVM. Observe the following program.

FileName: ExecuteMainMethodStaticBlock.java

Output:

Inside the static block.
Inside the main method
Inside the main method

Explanation: A static block is executed first, and in that block, the main() method is invoked explicitly. Again, JVM executes the main() method implicitly since the main() method serves as the entry of the program.

Approach: Using Recursion

It is a known fact that a method calls itself in recursion. Therefore, recursion can be applied to invoke the main method multiple times. An illustration of it is given below.

FileName: ExecuteMainMethodRecursion.java

Output:

Inside the main method.
Inside the main method.
Inside the main method.
Inside the main method.
Inside the main method.
?
?
?

Explanation: We have managed to execute the main() method multiple times using recursion. However, this program will not terminate as there is no terminating condition.

In order to terminate the program, we have to write a terminating condition. One can do that with the help of a static variable. Observe the following.

FileName: ExecuteMainMethodRecursion.java

Output:

Inside the main method.
Inside the main method.
Inside the main method.
Inside the main method.
Inside the main method.

Explanation: We have to use a static variable because the main() method is decorated with the static keyword. We want the recursion to occur only five times, and according to that, we have written the terminating condition.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA