Can we change the order of public static void main() to static public void main() in Java?

JavaObject Oriented ProgrammingProgramming

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 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.

Syntax

public static void main(String args[]) {
   // some statements
}

Example

Live Demo

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
raja
Published on 28-Jun-2019 14:44:02
Advertisements