Every standalone Java program starts in a class. The JVM looks for public static void main(String[] args) as the entry point—similar to how PHP scripts start at the top of a file, but Java requires an explicit method signature.
Minimal program structure
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
}
}
Public class name must match the filename. Save this as Main.java. A file cannot declare two public top-level classes.
Reading the main signature
public— JVM can call it from outside the classstatic— runs without creating an instance ofMainvoid— returns nothingString[] args— command-line arguments (often empty in the playground)
Important interview questions and answers
- Q: Why must main be static?
A: The JVM invokes main before any object exists; static methods belong to the class, not an instance. - Q: Can main be in any class?
A: Yes, but conventionally in a class named after the app; the playground expectsMain. - Q: What happens if the class name does not match the file?
A:javacfails with a compile error.
Self-check
- What three keywords appear before
void main? - Why is the class named
Mainin this track?
Tip: The public class name must match the filename—Main.java requires public class Main. Fix that before debugging logic errors.
Interview prep
- Why must main be static?
The JVM calls
mainbefore any instance of the class exists—static methods belong to the class itself.