Different Valid Forms of main() Method in Java
In Java, there are a few valid ways to declare the main()
method. Below are the accepted forms with examples.
1. Standard Form
public class StandardMain {
public static void main(String[] args) {
System.out.println("Standard main method");
}
}
2. String args[] (Array notation after name)
public class ArgsAfter {
public static void main(String args[]) {
System.out.println("Array after variable name");
}
}
3. static public instead of public static
public class StaticPublicMain {
static public void main(String[] args) {
System.out.println("Order of modifiers changed");
}
}
4. Custom name for args
public class CustomArgsName {
public static void main(String[] myInput) {
System.out.println("Custom argument name: " + myInput.length);
}
}
❌ Invalid Forms (Will NOT Work)
// Missing static
public class MissingStatic {
public void main(String[] args) {
System.out.println("This will not run");
}
}
📝 Summary Table
Declaration | Valid? | Notes |
---|---|---|
public static void main(String[] args) | ✅ | Standard and preferred |
public static void main(String args[]) | ✅ | Array notation position doesn't matter |
static public void main(String[] args) | ✅ | Order of modifiers doesn't matter |
public static void main(String[] input) | ✅ | Parameter name can be anything |
public void main(String[] args) | ❌ | Missing static |
static void main(String[] args) | ❌ | Missing public |