Does order of public static declaration matter in main method

Does order of public static declaration matter in main method

Answer: It does not matter and we can have at any place as you could see in example below:

package com.javahonk;

public class MainMethodTest {

   static public void main(String[] args) {
  System.out.println("Main method test");
  }

}

 

Reason:  When you compile java class JVM first checks if class and its method follow java specification or not and it gives compilation error to correct your class definition according to its specification. According to java specification all method should have return type and this should be put immediately after the method name then it checks if any access specifier has been mentioned or not. If no access specifier has been mentioned then it applies default access modifier which accessible only through sub class or in same package. For more details check Java Access Specifiers

I will say its by design, make easy to write class and its method also give programmer flexibility to make less mistake, so specification added to the compiler and it doesn’t bother about order or position. You could put access modifier either first or second position and same applies to the static keyword as well.

 

3 thoughts on “Does order of public static declaration matter in main method”
  1. 0 marks because you write that ” return type and this should be put immediately after the method name”
    it should be before the method name , not after

Leave a Reply

Your email address will not be published. Required fields are marked *