54

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?

Community
  • 1
  • 1
Campa
  • 4,267
  • 3
  • 37
  • 42

4 Answers4

75

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.

Mike Kwan
  • 24,123
  • 12
  • 63
  • 96
23

final refers to the variable, not the object, so yes, it make sense.

e.g.

final String s = "s";
s = "a"; // illegal
MByD
  • 135,866
  • 28
  • 264
  • 277
6

It makes sense. The final keyword prevents future assignments to the variable. The following would be an error in java:

final String x = "foo";
x = "bar" // error on this assignment
Colin D
  • 5,641
  • 1
  • 23
  • 35
6

References are final, Objects are not. You can define a mutable object as final and change state of it. What final ensures is that the reference you are using cannot ever point to another object again.

Kalpak Gadre
  • 6,285
  • 2
  • 24
  • 30
  • What I understand from this answer; Due to String is immutable, when we change its content, it will point another object. So, if a string is final then reassignment will not work. But in the case of StringBuffer, it is mutable then we can change its content. Is it right? – ceyun Apr 26 '20 at 20:15