Java: What does final mean, and are final variables always immutable?

A final variable can not be changed after it has been initialized.

Example:

class C {
    void m() {
        final int i = 7;
        i = 55;Error: i has already been initialized.



    }
}

So final in the example above, makes i immutable.

The exact same rules apply for reference types (Object, String, List, int[] etc). See this example:

class IntBox {
    int j = 17;
}

class C {
    void m() {
        final int i = 7;
        final IntBox b = new IntBox();
    }
}

This creates the situation depicted below (locations made up, not actual memory layout):

So, both i and b are final. Are both immutable?

Strictly speaking, yes, since neither i nor b can change their value both are immutable. However, when you mention b in everyday conversation, you’re rarely talking about the reference it contains, 0x1153, but the object that the reference points to, the IntBox object. Since the j field is not final (i.e. the IntBox object is mutable) most people would say that b is also mutable.

You could think of it as i “as a whole” can not change and is therefore immutable, but b “as a whole” can change and is therefore mutable.

Comments

Be the first to comment!