I want to know if the "Java main method" is the only way to create a main method in java.
The Java main method:
public class Test {
public static void main(String args[]) {
//example code
}
}
I want to know if the "Java main method" is the only way to create a main method in java.
The Java main method:
public class Test {
public static void main(String args[]) {
//example code
}
}
JVM requires an entry point to start the execution and this entry point is defined as below in JVM
public static void main(String[] args)
So to answer your question, you can define a main
method with any access modifier or with/without static
keyword, but then it is not a valid main method, as the main method which the JVM uses as an entry-point should be defined as such.
Equivalenty, yes, but syntactically - NO!
All of these are valid:
public static void main(String[] args)
public static void main(String[] foo)
public static void main(String... args)
Notice they are all an effectively equivalent method signature.
edit: one more -
public static void main(String args[])
edit: for interest's sake, final is implicit but can be added
public static final void main(String[] args) {
Final note: even though variations are valid, it's usually best to stick with convention and go with the default.
There was the hackish version removed in java7, leveraging static initializers.
In java8 the initializer will still takeover, but needs an unused main
method.
Not for actual use :)
public class Test {
static {
System.out.println("Hello world");
System.exit(0);
}
}
You can create as many variations of main() methods you want like:-
int main(int i){...}
String main(){...}
etc....
But
public static void main(String args[]) {...} // JVM will call only this main method
This will be only considered as entry point to program.