Initializing static final fields using a static initializer

suggest change

To initialize a static final fields that require using more than a single expression, a static initializer can be used to assign the value. The following example initializes a unmodifiable set of Strings:

public class MyClass {

    public static final Set<String> WORDS;
    
    static {
        Set<String> set = new HashSet<>();
        set.add("Hello");
        set.add("World");
        set.add("foo");
        set.add("bar");
        set.add("42");
        WORDS = Collections.unmodifiableSet(set);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents