I'm declaring a field:
private static final String filename = "filename.txt";
First, does the order of private static final
matter? If not, is there a standard accepted sequence or convention?
Second, the filename
in my application is fixed. Is this the best was to store its value?
private static final will be considered as constant and the constant can be accessed within this class only. Since, the keyword static included, the value will be constant for all the objects of the class. private final variable value will be like constant per object. You can refer the java.
A developer needs to combine the keywords static final to achieve this in Java. The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed.
The main difference between static and final is that the static is used to define the class member that can be used independently of any object of the class. In contrast, final is used to declare a constant variable or a method that cannot be overridden or a class that cannot be inherited.
In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.
I use Checkstyle with Eclipse, which results in a warning if the declaration is in a different order to the one you've specified, citing the Java Language Specification (JLS). For example,
private final static String filename = "filename.txt";
results in
'static' modifier out of order with the JLS suggestions.
They have this page which lists the order they expect, though following the links on that page through to the JLS I can't see anything to back up their assertion of a suggested order.
Having said that, the order they suggest seems to correspond to the order in most of the code I've seen, so it seems as good a convention as any to adopt.
No. But that is the sequence I usually see used.
It's a reasonable choice, but some would prefer a configuration file, either Properties or another file format (e.g. XML). That way, you can change the filename without recompiling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With