when exactly are we supposed to use "public static final String"?
final
indicates 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 String
when you want to create a String
that:
- belongs to the class (
static
: no instance necessary to use it), that - won't change (
final
), 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, and that - will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
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.
Finally note that final
will only make truly constant values out of primitive types and String
which is immutable. Applying final
to an object (for instance a HashMap
) 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.
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.
- Static means..You can use it without instantiate of the class or using any object.
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest { static final String str = "Hello"; public static void main(String args[]) { // str = "world"; // gives error System.out.println(str); // called without the help of an object System.out.println(StringTest.str);// called with class name } }
Thanks