1

Possible Duplicate:
What's the advantage of a String be Immutable?

Strings are Immutable?

String s = "PROJECT";

Here s cannot be modified. But String s2=s.toLowerCase() will return me a new string. Here still I can get a new copy of the original string! But if Java still wants immutability, then why not restrict the user while modifying the string (throw an exception or something). Then why immutability? Can any one explain why?

Community
  • 1
  • 1
Pradeep Kumar
  • 471
  • 2
  • 6
  • 14
  • 2
    There are many advantages to immutability. See this [SO question](http://stackoverflow.com/questions/214714/mutable-vs-immutable-objects) and [this one too](http://stackoverflow.com/questions/3407403/whats-the-advantage-of-a-string-be-immutable) – Ray Toal Sep 21 '11 at 06:48
  • 3
    Woah! Easy on the exclamation marks there! You might hurt yourself. – Joachim Sauer Sep 21 '11 at 06:50
  • 3
    "_Here s cannot be modified.But String s2=s.toLowerCase() will return me a new string._" Thats the point of immutability . If it was mutable , it could return the same string , value changed . – amal Sep 21 '11 at 06:53
  • It is important not to confuse `s` which is a reference to a String, which is not immutable in this example, and the String referenced which is immutable. In other languages, a reference might have a special notation like `&`, however in Java it is the only option for referring to an Object. – Peter Lawrey Sep 21 '11 at 07:38

2 Answers2

5

There's a little misconception:

s isn't immutable. s can easily be assigned a new value (i.e. another refence to another String object) unless it is final.

And just because a String instance is immutable doesn't mean that you can't make another String that derives its value from that first String instance but is slightly different.

In fact that's the only way how you can "modify" strings in Java: you can't change the content of any given String object, but you can create a copy that has modified content (that copy is then again immutable!).

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
3

Strings are immutable, meaning that this is always true:

String s = "PROJECT";
String s2 = s.toLowerCase();

System.out.println(s.equals("PROJECT")); // Prints true
System.out.println(s.equals(s2));        // Prints false

In comparison, consider what would happen if Strings were mutable.

MutableString ms = "PROJECT";
MutableString ms2 = ms.toLowerCase();

System.out.println(ms.equals("PROJECT")); // Prints false
System.out.println(ms.equals(ms2));       // Prints true

This example may seem trivial, but it means that unless you actually re-assign the reference s then you can guarantee that s will not be changed by any piece of code.