Skip to content
Advertisement

Are non-static final variables useful in Java?

This question discusses the practices of non-static final variables.

My first impression is that non-static final variables are useless because final variables cannot be reassigned after initialization.

class Foo {
    public static final int BAR = 10;
}

That would mean all the objects created from type Foo would have BAR = 10.

When would it be useful, practical, or accepted to use non static, but final variables, like so?

class Foo {
    public final int BAR = 10;
}

So in what case does the latter become useful? Since it basically means the same thing.

Advertisement

Answer

final in Java is not to be confused with const in C++. Declaring a variable final means that it cannot be reassigned. If the variable is a primitive type, this is fine. If the variable is a reference type, declaring it final does not prevent it from mutating.

This is safe (as int is a primitive type) and commonly accepted:

class Week {
    public static final int NUMBER_OF_DAYS = 7;
}

Week.NUMBER_OF_DAYS = 6;  // error: cannot reassign final variable

This is also safe. While java.lang.String is not a primitive type, it is guaranteed to be immutable. (Ie String has no method that changes its value and it must never get one or a quite fundamental language-level contract will be broken.) I still find that many people dislike this use of public attributes and many style guides ban it.

class Weekday {
    public final String name;

    public Weekday(String name) {
        this.name = name;
    }
}

Weekday monday = new Weekday("Monday");
monday.name = "Tuesday";  // error: cannot reassign final variable

This is not safe:

class Week {
    public static final String[] DAYS_OF_THE_WEEK = {
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday",
    };
}

Week.DAYS_OF_THE_WEEK = new String[6];  // error: cannot reassign final variable
Week.DAYS_OF_THE_WEEK[2] = "February";  // this is not prevented!

Using a java.util.Collection would not have made the last example much better. There are Collections that amputate all mutating methods but the only thing this will buy us is a run-time error. The compiler can’t help here.

Advertisement