Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to define a static final variable in Java?

Tags:

java

Does this definition make sense ?

private static final String string = "Constant string";

I'm a beginner and I don't understand the difference between final and static...

like image 581
Abramodj Avatar asked Mar 02 '11 14:03

Abramodj


2 Answers

It makes sense, yes. This is how constants are defined in Java.

  • final means that the variable cannot be reassigned - i.e. this is the only value it can have
  • static means that the same value is accessible from each instance of the class (it also means it can be accessed even without an instance of the class where it is declared)

(private here means this constant is accessible only to the current class (all of its instances and its static methods))

like image 198
Bozho Avatar answered Sep 30 '22 17:09

Bozho


Yes, it makes sense - this is how constants are usually defined in Java.

final means that you cannot change the variable to a different String.

static means that there is only one copy of the reference, shared between different objects of that class. (reference)

Normal code-convention is that constants are named in uppercase with underscores between words, so I would say:

private static final String CONSTANT_STRING = "Constant string";

is more common.

like image 34
Matthew Gilliard Avatar answered Sep 30 '22 18:09

Matthew Gilliard