and has a predefined method in it: public static void main(String[] args)
So why and what is this public static void main(String[] args)... we will see below.
public
This is the access modifier of the main method. It has to be public so that java runtime can execute this method. If we make any method non-public then it’s not allowed to be executed by any program. Some access restrictions are applied. So it means that the main method has to be public.
Let’s see what happens if we don't define public
As we see, it throws and Error
Error: Main method not found in class com.checker.TestCheck, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
static
When java runtime starts, there is no object of the class present. That’s why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won’t be static, JVM would not be able to call it because there is no object of the class is present.
Let’s see what happens when we remove static from java main method.
And after running this code
Error: Main method is not static in class com.checker.TestCheck, please define the main method as:
public static void main(String[] args)
void
In Java it's mandateory that every method provide the return type. Java main method doesn’t return anything, that’s why it’s return type is void. This has been done to keep things simple because once the main method is finished executing, java program terminates.
main
This is the name of java main method. It’s fixed and when we start a java program, it looks for the main method.
Let's see what happens when we change the "main"
Here main has been changed to maintest.
Following error occurred...
Error: Main method not found in class com.checker.TestCheck, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
String[] args
Java main method accepts a single argument of type String array. This is also called as java command line arguments.
No comments:
Post a Comment