HomeLanguagesJavaExecute main() multiple times without using any other function or condition or...

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:




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


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.

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32745 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7131 POSTS0 COMMENTS
Nicole Veronica
12258 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12345 POSTS0 COMMENTS
Shaida Kate Naidoo
7240 POSTS0 COMMENTS
Ted Musemwa
7504 POSTS0 COMMENTS
Thapelo Manthata
7224 POSTS0 COMMENTS
Umr Jansen
7190 POSTS0 COMMENTS