Change Order of public static void main in Java



Yes, we can change the order of public static void main() to static public void main() in Java, the compiler doesn't throw any compile-time error or runtime error. In Java, we can declare access modifiers in any order, the method name comes last, the return type comes second to last and then after it's our choice. But it's recommended to put access modifier (public, private and protected) at the forefront as per Java coding standards.

Java Method Modifiers and Their Order

Java allows you to place method modifiers (the keyword "public," "static," "final," etc.) in various orders. The Java Language Specification states so in section 8.4.3,
"The order of modifiers in a method declaration is not significant."

Valid Variations of main()

All of these are syntactically correct:

public static void main(String[] args) // Standard convention
static public void main(String[] args) // Valid but less common
final public static void main(String[] args)    // Also valid
public final static void main(String[] args)    // Works fine

But Why Does the Order Not Matter?

The location of the Java modifiers does not need to be remembered due to the Java compiler's method of processing code. When the Java compiler encounters a method declaration, it parses it into its components, such as the access modifiers, the return type, the method name, and the parameter list. The location of the access modifiers does not need to be in a specific order as long as all of them are present.

What If We Remove a Modifier?

The main method must have:

  • public ? JVM needs access to call it.
  • static ? Called without creating an object.
  • void ? Returns nothing.

Invalid Examples (Won't Run)

Below are some invalid examples of modifiers:

public void main(String[] args)  // Missing 'static' ? Error  
static void main(String[] args)  // Missing 'public' ? Error  
public static int main(String[] args)  // Wrong return type ? Error  

Example

Below is an example of a static public void main() program in Java:

class ParentTest {
   int age = 10;
   public int getAge() {
      age += 25;
      return age;
   }
}
public class Test {
   // Here we can declare static public void main(String args[])
   static public void main(String args[]) {
      ParentTest pt = new ParentTest();
      System.out.println("Age is: "+ pt.getAge());
   }
}

In the above example, we have declared static public main() instead of public static void main(), the code runs successfully without any errors.

Output

Age is: 35
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-04-16T18:53:41+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements