Execute the Main Method Multiple Times in JavaIn this tutorial, we will see how one can execute the main() method multiple times in Java. Approach: Using Static BlockWe 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 RecursionIt 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. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India