Main Method &
Program Entry
Learn to create and run a Java program with the public static void main method: the gateway every Java application uses to start executing code.
What Is a Program Entry Point?
Every application needs a starting point: the first instruction the computer executes when you click "Run." In Java, that starting point is always a special method called main.
How the JVM Finds Your Code
The Java Virtual Machine (JVM) is the engine that runs your code. When you execute a program, the JVM searches for a method with the exact signature public static void main(String[] args) and begins execution there.
Why Every Java Program Needs main
The Exact Signature
public static void main(String[] args)
Breaking Down Each Keyword
static vs Instance Methods
| static Method | Instance Method | |
|---|---|---|
| Belongs to | The class itself | An object (instance) |
| Called via | ClassName.method() | object.method() |
| Object needed? | No | Yes |
| Why main uses it | JVM must call main before any objects exist | |
Writing Your First Program
Example 1: Hello World
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Example 2: Using Command-Line Args
public class Greeter { public static void main(String[] args) { if (args.length > 0) { System.out.println("Hello, " + args[0] + "!"); } else { System.out.println("Hello, stranger!"); } } }
Example 3: Calling Other Methods
public class Calculator { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = add(5, 3); System.out.println("Sum: " + result); } }
Anatomy of a Java Program
What Happens Without main?
public class Broken { public void greet() { System.out.println("Hi!"); } }
This compiles successfully with javac, but when you try to run it with java, the JVM throws an error because it cannot find the entry point.
Understanding String[] args
Common Mistakes
Signature Cheat Sheet
| Keyword | Meaning | What Happens If Changed |
|---|---|---|
| public | JVM can access it | JVM can't find method |
| static | No object required | Runtime error: no main |
| void | Returns nothing | Signature mismatch |
| main | Entry point name | JVM doesn't find entry |
| String[] args | CLI arguments | Wrong parameter type |
Question 1 of 5
Which of the following is the correct signature for a Java program's entry point?
Question 2 of 5
Why must the main method be declared static?
Question 3 of 5
Consider this code:
public class Demo {
public static void Main(String[] args) {
System.out.println("Hello!");
}
}
What happens when you run java Demo?
Question 4 of 5
If you run java MyApp cat dog, what is the value of args[1]?
Question 5 of 5
Consider this code:
public class App {
public static void main(String[] args) {
greet();
}
public void greet() {
System.out.println("Hello!");
}
}
What happens when you compile and run this program?