Does it make sense to define a final String in Java?

Campa picture Campa · Apr 19, 2012 · Viewed 57.9k times · Source

Possible Duplicate:
String and Final

From http://docs.oracle.com/javase/6/docs/api/java/lang/String.html I can read that:

Strings are constant; their values cannot be changed after they are created. 

Does this mean that a final String does not really make sense in Java, in the sense that the final attribute is somehow redundant?

Answer

Mike Kwan picture Mike Kwan · Apr 19, 2012

The String object is immutable but what it is is actually a reference to a String object which could be changed.

For example:

String someString = "Lala";

You can reassign the value held by this variable (to make it reference a different string):

someString = "asdf";

However, with this:

final String someString = "Lala";

Then the above reassignment would not be possible and would result in a compile-time error.