Execute main() multiple times without using any other function or condition or recursion in Java

Given task is to execute main() multiple times without using any other function and without recursion() and without error. Given condition is that if executing main() n times then you can only call him (n-1) times.

Solution:

filter_none

edit
close

play_arrow

link
brightness_4
code

class Test {
  
    // static block
    static
    {
        main(new String[] { "Hello" });
    }
    public static void main(String[] args)
    {
        System.out.println("Hii");
    }
}

chevron_right


Output:



Hii
Hii

Explanation: Static block is executed even before the main() executed. Here first, main() get called by static block and then JVM(Java Virtual Machine) call the main(). So, main() is executed two times by calling only one time.

Write your Interview Experience or mail it to contribute@geeksforgeeks.org



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.