When should we use an uninitialized static final variable? I know that an uninitialized static final variable can only be assigned values in the static initializer block, but I can't think of any real use for this.
6 Answers
It's used when initializing the variable can't be done in a single line. For example:
private static final Map<String, String> CACHE;
static {
Map<String, String> cache = new HashMap<String, String>();
cache.put("foo", "bar");
cache.put("zim", "bam");
// lots of other entries
CACHE = Collections.unmodifiableMap(cache);
}
1 Comment
I assume you mean:
public static final Object obj;
with no initial value explicitly assigned?
You can assign it in the static block based on some computation that can only occur at runtime, like reading some property file to create an Application-wide constant that is not known at compile time.
2 Comments
null? Is this behaviour guaranteed in the specs? It seems to me that the default value is undefined because we wouldn't be able to read it before assignment in the first place (compiler error).final field and the spec says the default will never be observed for such fields. I have corrected my answer.Basically if you need to assign a value which can't be easily represented in a single expression. For example, you might want to perform some logic to build an immutable map, and then assign it.
Generally it's more readable to put the "building" logic into a separate static method, and use that in the normal assignment though:
private static final Map<String, String> FOO_MAP = buildFooMap();
Comments
Static+Final
In short,
Static - to make it as a class variable - Independent of the Object (Accessible to every object the same location always)
Final - to make it a constant.(If final is before a Variable ofcourse!)
Where do we need only static?
=> May be to count the number of instances an object.
Where do we need only final?
=> Well to make something constant!
Where do we need static+final?
=> Make the variable accessible to every object and to make a constant.As in creating a class for COLOR may be.
For blank static variables the initialization has be done by static block.
public class StaticDemo
{
private static final String name;
static
{
name = "yash";
}
}
and why to use blank one's? since may be you can't initialize at the beginning.I accept the previous one's.
Comments
If the initialiser for a static field can throw an exception you cannot initialise it in one line, you have to have a static block or a static method.
static finalvariable initialized tonull? Or do you just mean any kind ofstatic finalvariable (private static final,public static final, etc.)?