Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Beginner question about String[] args in the main method

So I just tried excluding String[] args from the main method

It compiled alright !

But JVM is showing an exception

Why did it compile when String[] args HAS to be included every time ?

What is going on here ? Why won't it show a compilation error ?

typing this made me think that may be compiler did not see it as THE main method ..is that so ?

If that is the case..why not ? I mean isn't there supposed to be just one main method that MUST have String[] args as the argument ?

like image 323
Serenity Avatar asked Nov 27 '22 08:11

Serenity


1 Answers

typing this made me think that may be compiler did not see it as THE main method ..is that so ?

Correct. There is no compile error because you're perfectly free to have all kinds of methods named main. But when you start the JVM and give it a "main class", then it will look for a method static public void main(String[]) in that class, and if it does not find such a method, it aborts with an exception.

This allows you to have multiple main methods in your program and is really the only thing that makes sense if you think about it: Applications can be composed from classes and JAR files from lots of different sources, written by different people at different times, so in many cases you can't really have a single, designated "main class" right from the start.

like image 136
Michael Borgwardt Avatar answered Dec 05 '22 17:12

Michael Borgwardt