main() method is the entry point of the program where the execution begins. When you run the code, the execution starts from the main() method. Without the main() method, program execution will not start (unless it’s a special framework or a servlet-based app).
Syntax:
public static void main(String[] args)
Java Main Method Example (Program)
public class HelloUser {
public static void main(String[] args) {
System.out.println("Hello, User!");
System.out.println("Let's learn how the main method works.");
}
}
Explanation of the program:
Every program starts with the class, When you save the file, the file name should be the same as the class name.
This example starts with the public class HelloUser:
public
– This means the class can be accessed from anywhere, ‘public’ is a keyword and it is not optional.class
– This is a keyword used to declare a class in Java.HelloUser
– This is the class name. You can customize it; for example: HelloJava
👉 check the full guide here– What Is Class In Java With Example?
Next, public static void main(String[] args)
public
– Here, it means method can be accessed from outside the classstatic
– It means we do not need to create an object to call the method.void
– It means the method does not return any value.main
– This is the name of the method. Execution starts here.String[] args
– It is used to receive command-line arguments, if any are provided.
Next,
System.out.println("Hello, User!");
System.out.println("Let's learn how the main method works.");
System.out.println
is used to print the message on the console.
When we run the program, the JVM calls the main method and starts execution.
JVM stands for java virtual machine.
Output:
After execution of above program below output will be printed on console.
Hello, User!
Let's learn how the main method works.