Skip to content
Related Articles

Related Articles

Improve Article
Execute main() multiple times without using any other function or condition or recursion in Java
  • Last Updated : 01 Apr, 2019

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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course. In case you are prepared, test your skills using TCS, Wipro, Amazon and Microsoft Test Serieses.

My Personal Notes arrow_drop_up
Recommended Articles
Page :