I am a biggner in java. I am going well with java. The problem is when we declare main function in java as main(String args). I am learning with bluej. It worked fine if I just write main(). So what's the difference between both.
1 Answer
public static void main(String[] args is the entry point (which can be final or not, doesn't matter) that the java tool and standard IDEs and such look for in the main class of a Java application. If you don't include the parameter declaration (the String[] args), the signature doesn't match the expectation of the java tool and so may not work.
main() will compile, because it's just a method, but won't work with the java tool and other tools following its conventions.
If BlueJ allows you to leave off the parameter declaration, that's behavior specific to the BlueJ tool.
So for instance, this compiles just fine:
public class Example { public static void main() { System.out.println("Hi"); } } It compiles to an Example class with a method called main. But if you try to run that via the java tool:
$ java Example Error: Main method not found in class Example, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
To make it compatible with the java tool, you need the parameter.
3 Comments
main() will compile, because it's just another method, it just won't work with the java tool or other tools that follow its convention for what the main method signature is. So if by "worked" you mean it ran your main method, that's a BlueJ thign, not standard. If by "worked" you just mean it compiled, well, that's just compiling.String[] args means, it is just an array of arguments that you can pass to your program. Usually helpful for developing command line tools.
String[] argsand it will compile fine, but when you run you will get an error. The main entry point must include that signature.main()method?public static void main(String[] args){main();}code implicitly to your class. But that behavior is not guaranteed with other IDEs so don't depend on it. Only entry point in Java application ispublic static void main(String[] args).