Final variable manipulation in Java

It means that if your final variable is a reference type (i.e. not a primitive like int), then it’s only the reference that cannot be changed. It cannot be made to refer to a different object, but the fields of the object it refers to can still be changed, if the class allows it. For example:

final StringBuffer s = new StringBuffer();

The content of the StringBuffer can still be changed arbitrarily:

s.append("something");

But you cannot say:

s = null;

or

s = anotherBuffer;

On the other hand:

final String s = "";

Strings are immutable – there simply isn’t any method that would enable you to change a String (unless you use Reflection – and go to hell).

Leave a Comment