Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick Java question about private static final keywords for fields

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?

like image 730
Spencer Avatar asked May 14 '10 06:05

Spencer


People also ask

Can we use private static final together in Java?

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.

Why we use private static final in 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.

What are the differences between private static and final variables?

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.

How do I change the value of the final static variable in Java?

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.


2 Answers

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.

like image 99
Hobo Avatar answered Sep 28 '22 13:09

Hobo


  1. No. But that is the sequence I usually see used.

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

like image 21
Matthew Flaschen Avatar answered Sep 28 '22 12:09

Matthew Flaschen