I have seen much code where people write public static final String mystring = ...
and then just use a value.
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
UPDATE
Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont understand is why people use that even if the constant will be used only in one place and only in the same class. why declaring it? why dont we just use the variable?
finalindicates that the value of the variable won’t change – in other words, a constant whose value can’t be modified after it is declared.Use
public final static Stringwhen you want to create aStringthat:static: no instance necessary to use it).final), for instance when you want to define aStringconstant that will be available to all instances of the class, and to other objects using the class.Example:
Similarly:
It isn’t required to use
final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.Even if the constant will only be used – read – in the current class and/or in only one place, it’s good practice to declare all constants as
final: it’s clearer, and during the lifetime of the code the constant may end up being used in more than one place.Furthermore using
finalmay allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.Finally note that
finalwill only make truly constant values out of primitive types,Stringwhich is immutable, or other immutable types. Applyingfinalto an object (for instance aHashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.