Are all final class immutable?

Further to the other responses, if you look at the code for java.lang.String you'll see it contains a field: hash, which is mutable and is in fact computed and stored when hashCode() is called for the first time.

However, the class is still immutable: The hash field cannot be accessed directly or modified outside of the class.

Also, you may notice a common approach within the JDK is the implementation of immutable wrappers that can be used to expose an object's internal state without allowing it to be modified; e.g.

private final List<String> values;

public List<? get String> getValues() {
  return Collections.unmodifiableList(values);
}

No - a final class means you cannot inherit from it. It has nothing to do with mutability. The following class is final yet mutable:

public final class FinalMutable {
  int value;
  public void setValue(int v) { value=v; }
  public int getValue() { return value; }
}

There is no keyword for immutability, it's more like a design pattern.

EDIT:
This means, there is no keyword, that makes a class immutable. To make a class immutable, you have to protect the internals by make them final or private.

The confusing thing is this: The final keyword has different meanings when used on a class then it has when used on a field/variable. The former means "this class can not be extended". The Second means "this variable (or reference) can not be changed".


No, final means the class can not be extended. It says nothing about mutability. For example:

final class MutInt {
   public int modifyMe;
}