The execution of any Java program starts with the Main method. This is the entry point of a Java program. When you create a Java application, the JVM looks for a main method with this specific signature to start the program.
Signature of Main method and its components
The following is the signature of a main method in a Java program –
public class MyHelloWorldExample {
public static void main(String[] args) {
// logic execution starts here
}
}
Let us look at each of the parts of Main method signature and see why it is designed as such.
public
It specifies from where and who can access the method. The main method must be declared as public so that it can be accessed by the JVM when starting the program.
static
To indicate that the main method belongs to the class rather than an instance of the class, you declare it as static. By making the class static, the JVM initializes the main method without creating any object for it.
void
The method does not return any value. Hence the return type is void here – It is used to specify that a method doesn’t return anything
main
The point from where the program starts its execution. The name of the method must be exactly “main.”
When you run an application with the Java command, the JVM looks for the main method in the program and starts execution from over there.
If no Main method is found, it’d throw a runtime error – “Main method not found in class” exception
String[] args
public class MyHelloWorldExample {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please input any number: ");
return;
}
try {
int inputValue = Integer.parseInt(args[0]);
// Process the integer value
System.out.println("You have entered: " + inputValue);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
}
}
}
represents the data passed through the Java command line arguments. It is an array of type java.lang.String
class. Passing any arguments to a Main method is optional and one doesn’t need to read the args if there’s no use case for it.
java MyHelloWorldExample 42