Every time I write method in Java with more keywords than public void
, every time I write it another way. Sometimes "static public void
" sometimes "public static void
" etc.
What is the best order (best practices) for these keywords?
[abstract/static
] [final
] [synchronized
] [public/private/protected
] [result_type
] ???
Yes, there is a standard ordering.
If you use an IDE, you can set it up to format your code for you, i.e. in Eclipse in Preferences -> Java -> Editor -> Save Actions you can check the box "Format source code"
Then you don't have to worry about it any more. It will be done automatically whenever the file is saved and if your whole project uses this, then for the whole project has code that is formatted in the same way.
The "best" would be to follow the Java Coding Style Guide, that states in 6.2 (method declaration):
Checkstyle (which implements the suggestions of the Java Language Specifications sections, 8.1.1, 8.3.1, and 8.4.3) says:
The best order is the one that the rest of your code uses.
The custom usage order of the modifiers is mentioned in the Java Language Specification (so no need to have an own opinion ;-)) e.g. for method modifiers you will find the following definition (extract):
You will find this sentence at several other places where the usage of modifiers is specified, e.g. here for field modifiers.
(This is mostly copied from another answer of mine here).
This is my personal choice
this seems in line too with the java documentation