![]() |
VOOZH | about |
In Java, Can we call the main() method of a class from another class?
OR
How to call 'public static void main(String[] args)' method from our code?
These are some questions that usually puzzles a Java programmer. This article aims to provide an answer to these problems in a simple and efficient way.
As we know, the main() method for any Java application as the Java Run time environment calls the main() method first. So it is obvious that we don't need to call the main() method by ourselves as it is already called when the program starts. But what if we want to call the main() method from somewhere in our program? That's the problem.
Solution:
Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.
But calling the main() method from our code is tricky. It can lead to many errors and exceptions, such as:
prog.java:27: error: non-static method mainCaller()
cannot be referenced
from a static context
mainCaller();
^
1 error
prog.java:17: error: method main in class GFG
cannot be applied to given types;
main();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
RunTime Error in java code :-
Exception in thread "main" java.lang.StackOverflowError
mainCaller!
main
mainCaller!
main
mainCaller!
main
.
.
.
The right way to this:
Example 1: Calling main() method externally from the same class
Output:
main
mainCaller!
main
mainCaller!
main
mainCaller!
Example 1: Calling main() method externally from another class
Output:
main
mainCaller!
main
mainCaller!
main
mainCaller!