Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final static vs static final variables [duplicate]

Tags:

java

static

final

I have the following compiling code:

final static String test = "A";
static final String test2 = "B";

And everything compiles fine. My question is, what is the difference between these two?

like image 669
David says Reinstate Monica Avatar asked Dec 09 '22 14:12

David says Reinstate Monica


1 Answers

The order of those modifiers isn't mandatory, as stated in the Java Specification :

FieldModifiers: FieldModifier FieldModifiers FieldModifier

FieldModifier: one of Annotation public protected private static final transient volatile

But please note that the Java Specification introduces a best practice :

If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.

Which means that the most correct solution is

static final String test2 = "B";

The fact most coders respect this "custom" means that their fellow coders parse and read the code faster and with greater ease.

like image 169
Denys Séguret Avatar answered Jan 03 '23 14:01

Denys Séguret