Exploring Main Method
Key Points
main()method is a special method which will be called by the JVM.- Standard signature of
main():
public static void main(String[] args) { }
static public void main(String[] args) { }
✔ Order of public and static can be changed.
🔹 Important Notes
- You can overload the
main()method 👉 But JVM always calls only:
public static void main(String[] args)
main()acts as: 👉 Application launcher / entry point
📘 Explanation of main() Components
| Keyword | Meaning |
|---|---|
| public | Accessible from anywhere |
| static | Can be accessed without object (using class name) |
| void | Does not return any value to JVM |
| main | Method name (entry point) |
| String[] | Used to pass command-line arguments |
Lab410.java
class Lab410 {
static {
System.out.println("I am S.B");
}
public static void main(String[] args) {
// INVALID
System.out.println("I am main()");
}
}
Output:
- Runtime Error → No proper main method
Lab411.java
class Lab411 {
static {
System.out.println("I am S.B");
}
public static void main(String[] args) {
System.out.println("I am main()");
}
}
Output:
I am S.B
I am main()
Lab412.java
class Lab412 {
public static final synchronizedstrictfpvoidmain(String... args) {
System.out.println("I am main()");
}
}
Notes:
- Multiple modifiers allowed
String... args(var-args) is valid alternative
Lab413.java
class Lab413 {
public static void main(String[] args) {
System.out.println("main(String)");
}
public static void main(String[] args) {
System.out.println("main(String[])");
}
public void main(int[] args) {
System.out.println("main(int[])");
}
}
Output:
main(String[])
Key Concept:
- JVM calls only:
public static void main(String[] args)
- Other overloaded methods are ignored unless called manually
🧠 Summary
- ✔
main()= Entry point of Java program - ✔ Must be
public static void - ✔ Parameter must be
String[](orString...) - ✔ Overloading allowed but JVM ignores them
Lab414.java
class Lab414 {
public static void main(String[] args) {
System.out.println("main(String)");
}
public void main(int[] args) {
System.out.println("main(int[])");
}
}
Lab415.java
class Lab415 {
{
System.out.println("Lab415-I.B");
}
Lab415() {
System.out.println("Lab415-D.C");
}
public static void main(String[] args) {
System.out.println("main(String[])");
}
}
Lab416.java
class Hello {
public static void main(String[] args) {
System.out.println("Hello - main");
}
}
class Hai {
public static void main(String[] args) {
System.out.println("Hai - main");
Hello.main(args);
}
}