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?
final
indicates that the value of the variable won't change - in other words, a variable who's value can't be modified after it is declared.Use
public final static String
when you want to create aString
that:static
: no instance necessary to use it), and thatfinal
), for instance when you want to define aString
constant 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
final
may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.static
means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.Usually it's best to use final when you expect it to be
final
so that the compiler will enforce that rule and you know for sure.static
ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.
And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).
Hope it helps.