calling main method inside main in java

跟風遠走 提交于 2019-12-23 18:42:07

问题


Can we call main method inside main?

public static void main(String[] args) {
    main({"a","b","c"});
}

Tried to google.Can't find the link. Sorry if the question is trivial


回答1:


You can but using the correct format

main(new String[] {"a","b","c"});

should give StackOverFlowError (not tested)




回答2:


You will get StackOverFlowError. If you call endless recursive calls/deep function recursions.

Thrown when a stack overflow occurs because an application recurses too deeply.

You need to pass String array like

main(new String[] {"a","b","c"});



回答3:


You can. And it is very much legal.
Also, it doesn't necessarily give a StackOverFlowError:

public static void main(String args[]){

    int randomNum = (int)(Math.random()*10);

    if(randomNum >= 8)
    System.exit(0);

    System.out.print("Heyhey!");
    main(new String[]{"Anakin", "Ahsoka", "Obi-Wan"});

}

Just saying.




回答4:


Kugathasan is right.

Yes it does give StackOverflow Exception. I tested it right now in Eclipse.

class CallingMain
{
    public static void main(String[] args)
    {
         main(new String[] {"a","b","c"});
    }
}

I have one suggestion, I think the best way to eliminate the confusion is to try coding and running it. Helps with lots of doubts.




回答5:


You can simply pass the argument like main(new String[1]) - this line will call main method of your program. But if you pass "new String[-1]" this will give NegativeArraySizeException. Here I'mm giving an example of Nested Inner Class where I am calling the Main method:

class Outer 
{
    static class NestedInner
    {

        public static void main(String[] args)
        {
            System.out.println("inside main method of Nested class");

        }//inner main
    }//NestedInner
    public static void main(String[] args) 
    {

        NestedInner.main(new String[1] );//**calling of Main method**
        System.out.println("Hello World!");
    }//outer main
}//Outer

Output:- inside main method of Nested class

Hello World!



来源:https://stackoverflow.com/questions/21992659/calling-main-method-inside-main-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!