1

I know String is immutable but why?

Which concept makes string class immutable?

public class Mainclass
{
    public static void main(String[] args) 
    {
        String s = "Example";
        s.toUpperCase();
        System.out.println(s);
    }
}

Result:

Example
Radiodef
  • 37,180
  • 14
  • 90
  • 125
Albertkaruna
  • 85
  • 2
  • 11
  • You should probably do : `string newString = s.toUpperCase()` , as .toUpperCase returns a new string object itself – Abhishek Ghosh Apr 13 '15 at 19:31
  • This is a duplicate of http://stackoverflow.com/questions/279507/what-is-meant-by-immutable. I'd flag it, but I raised the wrong one. – DavidS Apr 13 '15 at 21:17

4 Answers4

7

String is immutable because there is no way to change the contents of its internal representation, no way to gain a reference to its internal representation, and it cannot be subclassed. This means that no matter what you do to a String, you cannot change its contents.

What methods like toUpperCase() actually do is return a new String, which has the same contents as the old String. however, the new String is a separate object. references to the initial string will not now point to the new one.

If you wanted to print out the results of toUpperCase() then do so like the following:

String s="Example";
String upperCase = s.toUpperCase();
System.out.println(upperCase);

EDIT: references vs. objects

A variable in Java is a reference to an object. a recerence is essentially a pointer that tells Java "your object is here", referring to some memory location. However the reference and the object are not the same thing. Lets look at the following as an example

String s = "Test";
String a = s;
String s = "another test"

What I have done here is declared a reference called s, and set its pointer to a newly created object - in this case a String with value "Test". I then declare another reference a and set it to reference the same object that s references. Note, that there are two references but only one object.

From there I change the reference s to point to a different object - in this case a String with value "another test". This creates a new object, despite the reference being reused. However, the reference a still points to the original object, which has remained unchanged. if we do println(a) it will still print "Test". This is because the object itself is immutable. Anything that points to it will always return the same value. I can make the references point somewhere else, but cannot change the object.

Think about the variables like entries in a phone book. If I put in an entry for someone and say his last name is "BOB", and someone later comes along and crosses that out and writes "ALICE", this does not suddenly change Bob's gender, or his name. BOB does not spontaneously turn into ALICE because someone rewrote my phone book. It merely changes the value in my phone book, not the actual person. I hope this metaphor helps.

Davis Broda
  • 4,102
  • 5
  • 23
  • 37
  • String is immutable but following example change the value How it is possible? String s="Example"; s="Sample"; System.out.println(s); Result: Sample – Albertkaruna Apr 13 '15 at 19:28
  • @Albertkaruna I have no idea what your comment is supposed to signify. Please clarify your comment so that I can coherently respond to it. – Davis Broda Apr 13 '15 at 19:30
  • @Albertkaruna The object is still immutable, you just make `s` to point to a different reference. – Bubletan Apr 13 '15 at 19:35
  • Now i understood. But String is mostly used for security purpose, now i changed my reference to some other object. How can i get my original object("Example object")? – Albertkaruna Apr 13 '15 at 19:42
  • @Albertkaruna You need to understand difference between value and variable (object and reference). If state of object can't be changed then we say it is *immutable*, if variable can't be reassign to different object it means it is *final*. Just because you can assign new value to variable doesn't mean that state of old value has changed. – Pshemo Apr 13 '15 at 19:43
  • @Albertkaruna edited something in to describe the difference between references and objects. hope that helps – Davis Broda Apr 13 '15 at 19:48
  • Thanks for your help now i understood many things about String class. – Albertkaruna Apr 13 '15 at 19:57
  • @DavisBroda Plus references are stored on stack while object is stored on heap. In case of string, it's a separate matter, when we do String s = "Example", this will create the string literal in String constant pool. – SSC Apr 13 '15 at 19:58
2

Any class which cannot be subclassed and doesn't provide any way to modify its state -- e.g. by not providing any setters, keeping its fields private, etc. -- is immutable. There's no special magic.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

these are the steps by which you can make any type/class as immutable

1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.

2) Make all fields final and private.

3) Don’t allow to be sub class, make class final.

4) Special attention when having mutable instance variables.

Prashant
  • 2,556
  • 2
  • 20
  • 26
0

One of the reasons is security. Parameters for network connection are type of String. It should not be easy to be modified.

OHNH
  • 84
  • 1
  • 9