Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use an uninitialized static final variable?

Tags:

java

final

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.

like image 414
Sonoo Jaiswal Avatar asked Jan 31 '12 17:01

Sonoo Jaiswal


1 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);
}
like image 141
JB Nizet Avatar answered Oct 07 '22 11:10

JB Nizet