Reputation: 315
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
Upvotes: 4
Views: 27001
Reputation: 1
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!
Upvotes: 0
Reputation: 717
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.
Upvotes: 5
Reputation: 525
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.
Upvotes: 1
Reputation: 159874
You can but using the correct format
main(new String[] {"a","b","c"});
should give StackOverFlowError (not tested)
Upvotes: 17
Reputation: 32498
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"});
Upvotes: 4