← Back to Chapters

Java main() Method in Detail

? Java main() Method in Detail

? Quick Overview

The main() method is the entry point of any Java application. When you run a Java program, the JVM starts execution from this method. Without it, a Java program cannot run independently.

? Key Concepts

  • Entry point of Java program
  • Must be public and static
  • Returns void
  • Accepts command-line arguments
  • Called automatically by JVM

? Syntax / Theory

The standard syntax of the Java main() method is fixed so that the JVM can locate and execute it correctly. Each keyword has a specific purpose.

  • public → Accessible by JVM from anywhere
  • static → Can be called without creating an object
  • void → Does not return any value
  • String[] args → Stores command-line arguments
? View Code Example
// Basic structure of main method in Java
public class MainExample {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}

? Live Output / Explanation

? Output

When the program runs, the JVM finds the main() method and executes the statement inside it. The text Hello, Java! is printed on the console.

? More Variations of main()

? View Code Example
// main method with command-line arguments
public class ArgsExample {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}

? Tips & Best Practices

  • Always keep the method signature exactly correct
  • Use meaningful class names
  • Handle command-line arguments safely
  • Keep main() simple and delegate logic to other methods

? Try It Yourself

  • Create a program that prints your name using main()
  • Pass two numbers as arguments and print their sum
  • Check what happens if public is removed
  • Experiment with multiple classes having main()