4

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

5
  • 2
    Don't google it, just try it and see what happens. What do you think will happen? Commented Feb 24, 2014 at 16:00
  • 1
    Resulting in compliation error Commented Feb 24, 2014 at 16:01
  • You should look up array initialization expressions. Commented Feb 24, 2014 at 16:01
  • 4
    Why is this question -3 , it's reasonable Commented Feb 24, 2014 at 16:02
  • 7
    @Coffee: probably because there is zero effort put into it. Fixing the syntax and executing it would have answered it way faster. Commented Feb 24, 2014 at 16:03

5 Answers 5

17

You can but using the correct format

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

should give StackOverFlowError (not tested)

Sign up to request clarification or add additional context in comments.

1 Comment

It's StackOverFlowError
5

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.

Comments

4

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"}); 

Comments

1

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.

Comments

0

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!

3 Comments

No, you cannot! Whereas the compiler won't complain, the recursion you create would exhaust the stack quite fast.
this code is not for recursion, this is simple code for calling How to call Main method
What is it when you call main from main?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.