238

Consider the following example.

String str = new String();

str  = "Hello";
System.out.println(str);  //Prints Hello

str = "Help!";
System.out.println(str);  //Prints Help!

Now, in Java, Strings are immutable. Then how come the object str can be assigned with a different value like "Help!". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?

Edit:

Ok. I am now getting it, but just one follow-up question. What about the following code:

String str = "Mississippi"; 
System.out.println(str); // prints Mississippi 

str = str.replace("i", "!"); 
System.out.println(str); // prints M!ss!ss!pp! 

Does this mean that two objects are created again ("Mississippi" and "M!ss!ss!pp!") and the reference str points to a different object after replace() method?

2

26 Answers 26

348

str is not an object, it's a reference to an object. "Hello" and "Help!" are two distinct String objects. Thus, str points to a string. You can change what it points to, but not that which it points at.

Take this code, for example:

String s1 = "Hello";
String s2 = s1;
// s1 and s2 now point at the same string - "Hello"

Now, there is nothing1 we could do to s1 that would affect the value of s2. They refer to the same object - the string "Hello" - but that object is immutable and thus cannot be altered.

If we do something like this:

s1 = "Help!";
System.out.println(s2); // still prints "Hello"

Here we see the difference between mutating an object, and changing a reference. s2 still points to the same object as we initially set s1 to point to. Setting s1 to "Help!" only changes the reference, while the String object it originally referred to remains unchanged.

If strings were mutable, we could do something like this:

String s1 = "Hello";
String s2 = s1;
s1.setCharAt(1, 'a'); // Fictional method that sets character at a given pos in string
System.out.println(s2); // Prints "Hallo"

Edit to respond to OP's edit:

If you look at the source code for String.replace(char,char) (also available in src.zip in your JDK installation directory -- a pro tip is to look there whenever you wonder how something really works) you can see that what it does is the following:

  • If there is one or more occurrences of oldChar in the current string, make a copy of the current string where all occurrences of oldChar are replaced with newChar.
  • If the oldChar is not present in the current string, return the current string.

So yes, "Mississippi".replace('i', '!') creates a new String object. Again, the following holds:

String s1 = "Mississippi";
String s2 = s1;
s1 = s1.replace('i', '!');
System.out.println(s1); // Prints "M!ss!ss!pp!"
System.out.println(s2); // Prints "Mississippi"
System.out.println(s1 == s2); // Prints "false" as s1 and s2 are two different objects

Your homework for now is to see what the above code does if you change s1 = s1.replace('i', '!'); to s1 = s1.replace('Q', '!'); :)


1 Actually, it is possible to mutate strings (and other immutable objects). It requires reflection and is very, very dangerous and should never ever be used unless you're actually interested in destroying the program.

10
  • 17
    +1 for the fictional method, it demonstrates the differnce between immutable object and others.
    – Zappi
    Oct 12, 2009 at 8:15
  • 1
    Thanks gustafc for the correct examples and clear explanation....But can you just answer the edited part in the question please? That will make my understanding clear. Oct 12, 2009 at 17:30
  • 19
    I've never seen an answer like this before. Discussed every single detail. Aug 29, 2013 at 5:32
  • +1 Here's an idea, immutable objects in java are like copy-by-value, you can have 2 references to a String, but you should consider them 2 separate Strings since it's immutable, and working with one of them won't affect the other
    – Khaled.K
    Mar 27, 2014 at 12:01
  • 1
    Java-the more you think you know, the less you actually know.
    – zeeshan
    Mar 17, 2017 at 13:35
26

The object that str references can change, but the actual String objects themselves cannot.

The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable.

The immutability of String objects does not mean that the references pointing to the object cannot change.

One way that one can prevent the str reference from changing is to declare it as final:

final String STR = "Hello";

Now, trying to assign another String to STR will cause a compile error.

5
  • But in this case, the String object is 'str' which first contains the value 'Hello' and then gets assigned new value 'Help!'. What exactlyt do you mean by "The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable."??? Pardon me if this is a silly question. But iv got to clear it... Oct 12, 2009 at 2:29
  • 2
    have you perchance every tried to program in C? Just read the primer on pointers and you'll understand coobird's answer perfectly. Oct 12, 2009 at 2:58
  • See...This is what I want to avoid...I know you are a great programmer...and I am just trying to learn java here...So if you can answer my question correctly then please answer it... Oct 12, 2009 at 3:11
  • You're confusing references and objects - str isn't the "object" it's a reference to the object. If you have String str = "Hello"; followed by String anotherReference = str; you don't have 2 String objects, you have one object (the literal "Hello") and 2 references to it (str and anotherReference).
    – Nate
    Oct 12, 2009 at 11:05
  • I do not have the rights to edit, but if I did, I would edit coobirds 1st sentence to: "The str references can change, but the actual String objects themselves cannot."
    – j3App
    Nov 21, 2017 at 20:21
10

Light_handle I recommend you take a read of Cup Size -- a story about variables and Pass-by-Value Please (Cup Size continued). This will help a lot when reading the posts above.

Have you read them? Yes. Good.

String str = new String();

This creates a new "remote control" called "str" and sets that to the value new String() (or "").

e.g. in memory this creates:

str --- > ""

str  = "Hello";

This then changes the remote control "str" but does not modify the original string "".

e.g. in memory this creates:

str -+   ""
     +-> "Hello"

str = "Help!";

This then changes the remote control "str" but does not modify the original string "" or the object that the remote control currently points to.

e.g. in memory this creates:

str -+   ""
     |   "Hello"
     +-> "Help!"
2
9

Lets break it into some parts

String s1 = "hello";

This Statement creates string containing hello and occupy space in memory i.e. in Constant String Pool and and assigned it to reference object s1

String s2 = s1;

This statement assigns the same string hello to new reference s2

         __________
        |          |
s1 ---->|  hello   |<----- s2
        |__________| 

Both references are pointing to the same string so output the same value as follows.

out.println(s1);    // o/p: hello
out.println(s2);    // o/p: hello

Though String is immutable, assignment can be possible so the s1 will now refer to new value stack.

s1 = "stack";    
         __________
        |          |
s1 ---->|  stack   |
        |__________|

But what about s2 object which is pointing to hello it will be as it is.

         __________
        |          |
s2 ---->|  hello   |
        |__________|

out.println(s1);    // o/p: stack
out.println(s2);    // o/p: hello

Since String is immutable Java Virtual Machine won't allow us to modify string s1 by its method. It will create all new String object in pool as follows.

s1.concat(" overflow");

                 ___________________
                |                   |
s1.concat ----> |  stack overflow   |
                |___________________|

out.println(s1);    // o/p: stack
out.println(s2);    // o/p: hello
out.println(s1.concat); // o/p: stack overflow

Note if String would be mutable then the output would have been

out.println(s1);    // o/p: stack overflow

Now you might be surprised why String has such methods like concat() to modify. Following snippet will clear your confusion.

s1 = s1.concat(" overflow");

Here we are assigning modified value of string back to s1 reference.

         ___________________
        |                   |
s1 ---->|  stack overflow   |
        |___________________|


out.println(s1);    // o/p: stack overflow
out.println(s2);    // o/p: hello

That's why Java decided String to be a final class Otherwise anyone can modify and change the value of string. Hope this will help little bit.

6

The string object that was first referenced by str was not altered, all that you did was make str refer to a new string object.

0
5

The String will not change, the reference to it will. You are confusing immutability with the concept of final fields. If a field is declared as final, once it has been assigned, it cannot be reassigned.

5

Regarding the replace part of your question, try this:

String str = "Mississippi"; 
System.out.println(str); //Prints Mississippi 

String other = str.replace("i", "!"); 
System.out.println(str); //still prints Mississippi 
System.out.println(other);  // prints M!ss!ss!pp!
4

Though java tries to ignore it, str is nothing more than a pointer. This means that when you first write str = "Hello";, you create an object that str points to. When you reassign str by writing str = "Help!";, a new object is created and the old "Hello" object gets garbage collected whenever java feels like it.

3

Immutability implies that the value of an instantiated object cannot change, you can never turn "Hello" into "Help!".

The variable str is a reference to an object, when you assign a new value to str you aren't changing the value of the object it references, you are referencing a different object.

3

String class is immutable, and you can not change value of immutable object. But in case of String, if you change the value of string than it will create new string in string pool and than your string reference to that value not the older one. so by this way string is immutable. Lets take your example,

String str = "Mississippi";  
System.out.println(str); // prints Mississippi 

it will create one string "Mississippi" and will add it to String pool so now str is pointing to Mississippi.

str = str.replace("i", "!");  
System.out.println(str); // prints M!ss!ss!pp! 

But after above operation, one another string will be created "M!ss!ss!pp!" and it will be add to String pool. and now str is pointing to M!ss!ss!pp!, not Mississippi.

so by this way when you will alter value of string object it will create one more object and will add it to string pool.

Lets have one more example

String s1 = "Hello"; 
String s2 = "World"; 
String s = s1 + s2;

this above three line will add three objects of string to string pool.
1) Hello
2) World
3) HelloWorld

0
2

Use:

String s = new String("New String");
s.concat(" Added String");
System.out.println("String reference -----> "+s); // Output: String reference -----> New String

If you see here I use the concat method to change the original string, that is, "New String" with a string " Added String", but still I got the output as previous, hence it proves that you can not change the reference of object of String class, but if you do this thing by StringBuilder class it will work. It is listed below.

StringBuilder sb = new StringBuilder("New String");
sb.append(" Added String");
System.out.println("StringBuilder reference -----> "+sb);// Output: StringBuilder reference -----> New String Added String
2

Like Linus Tolvards said:

Talk is cheap. Show me the code

Take a look at this:

public class Test{
    public static void main(String[] args){

        String a = "Mississippi";
        String b = "Mississippi";//String immutable property (same chars sequence), then same object

        String c = a.replace('i','I').replace('I','i');//This method creates a new String, then new object
        String d = b.replace('i','I').replace('I','i');//At this moment we have 3 String objects, a/b, c and d

        String e = a.replace('i','i');//If the arguments are the same, the object is not affected, then returns same object

        System.out.println( "a==b? " + (a==b) ); // Prints true, they are pointing to the same String object

        System.out.println( "a: " + a );
        System.out.println( "b: " + b );

        System.out.println( "c==d? " + (c==d) ); // Prints false, a new object was created on each one

        System.out.println( "c: " + c ); // Even the sequence of chars are the same, the object is different
        System.out.println( "d: " + d );

        System.out.println( "a==e? " + (a==e) ); // Same object, immutable property
    }
}

The output is

a==b? true
a: Mississippi
b: Mississippi
c==d? false
c: Mississippi
d: Mississippi
a==e? true

So, remember two things:

  • Strings are immutable until you apply a method that manipulates and creates a new one (c & d cases).
  • Replace method returns the same String object if both parameters are the same
1

For those wondering how to break String immutability in Java...

Code

import java.lang.reflect.Field;

public class StringImmutability {
    public static void main(String[] args) {
        String str1 = "I am immutable";
        String str2 = str1;

        try {
            Class str1Class = str1.getClass();
            Field str1Field = str1Class.getDeclaredField("value");

            str1Field.setAccessible(true);
            char[] valueChars = (char[]) str1Field.get(str1);

            valueChars[5] = ' ';
            valueChars[6] = ' ';

            System.out.println(str1 == str2);
            System.out.println(str1);
            System.out.println(str2);           
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}

Output

true
I am   mutable
I am   mutable
0

String is immutable. Which means that we can only change the reference.


String a = "a";
System.out.println("String a is referencing to "+a); // Output: a

a.concat("b");
System.out.println("String a is referencing to "+a); // Output: a

a = a.concat("b");
System.out.println("String a has created a new reference and is now referencing to "+a); // Output: ab
0

In Java, objects are generally accessed by references. In your piece of code str is a reference which is first assigned to "Hello" (an automatic created object or fetched from constant pool) and then you assigned another object "Help!" to same reference. A point to note is the reference is the same and modified, but objects are different. One more thing in your code you accessed three objects,

  1. When you called new String().
  2. When you assigned "hello".
  3. When you assigned "help!".

Calling new String() creates a new object even if it exists in string pool, so generally it should not be used. To put a string created from new String () into string pool you can try the intern() method.

I hope this helps.

0

Immutability I can say is that you cannot change the String itself. Suppose you have String x, the value of which is "abc". Now you cannot change the String, that is, you cannot change any character/s in "abc".

If you have to change any character/s in the String, you can use a character array and mutate it or use StringBuilder.

String x = "abc";
x = "pot";
x = x + "hj";
x = x.substring(3);
System.out.println(x);

char x1[] = x.toCharArray();
x1[0] = 's';
String y = new String(x1);
System.out.println(y);

Output:

hj
sj
0

Or you can try:

public class Tester
{
public static void main(String[] args)
{
 String str = "Mississippi"; 
 System.out.println(str); // prints Mississippi 
 System.out.println(str.hashCode());

 str = str.replace("i", "!"); 
 System.out.println(str); // prints M!ss!ss!pp! 
 System.out.println(str.hashCode());
 }
 }

This will show how the hashcode changes.

0

String is immutable means that you cannot change the object itself, but you can change the reference to the object. When you called a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty". Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:

Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"

While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:

String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"
0

Here immutability means that instance can point to other reference but the original content of the string would not be modified at the original reference. Let me explain by first example given by you. First str is pointing to "Hello" ,its Ok upto this. Second time its pointing to "Help!". Here str started pointing to "Help!" and the reference of "Hello" string is lost and we can not get that back.

In fact when str would try to modify the existing content,then another new string will be generated and str will start to point at that reference. So we see that string at original reference is not modified but that is safe at its reference and instance of object started pointing at different reference so immutability is conserve.

0

Super late to the answer, but wanted to put a concise message from author of the String class in Java

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

It can be derived from this documentation that anything that changes string, returns different object (which could be new or interned and old). The not so subtle hint about this should come from the function signature. Think about it, 'Why did they make a function on an object return an object instead of status?'.

public String replace(char oldChar, char newChar) 

Also one more source which makes this behaviour explicit (From replace function documentation)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Source: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)

  • author Lee Boynton
  • author Arthur van Hoff
  • author Martin Buchholz
  • author Ulf Zibis

Source: JavaDoc of String.

0

The Object string - methods itself is made to be "immutable". This action produces no changes: "letters.replace("bbb", "aaa");"

But assigning data does cause changes to the Strings content to change:

    letters = "aaa";
    letters=null;
    System.out.println(letters);
    System.out.println(oB.hashCode());
    System.out.println(letters);
    letters = "bbbaaa";
    System.out.println(oB.hashCode());
    System.out.println(letters);

//The hashcode of the string Object doesn't change.

0

If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

You can have multiple pointer String variable to point HELLO String.

But if HELLO is char Array then you can change HELLO to HILLO. Eg,

char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this

Programming languages have immutable data variables so that it can be used as keys in key, value pair.

0

I would explain it with simple example


consider any character array : e.g. char a[]={'h','e','l','l','o'}; and a string : String s="hello";


on character array we can perform operations like printing only last three letters using iterating the array; but in string we have to make new String object and copy required substring and its address will be in new string object.

e.g.

***String s="hello";
String s2=s.substrig(0,3);***

so s2 will have "hel";

-1

String in Java in Immutable and Final just mean it can't be changed or modified:

Case 1:

class TestClass{  
 public static void main(String args[]){  
   String str = "ABC";  
   str.concat("DEF");  
   System.out.println(str);  
 }  
} 

Output: ABC

Reason: The object reference str is not changed in fact a new object "DEF" is created which is in the pool and have no reference at all (i.e lost).

Case 2:

class TestClass{  
 public static void main(String args[]){  
   String str="ABC";  
   str=str.concat("DEF");  
   System.out.println(str);  
 }  
}  

Output: ABCDEF

Reason: In this case str is now referring to a new object "ABCDEF" hence it prints ABCDEF i.e. previous str object "ABC" is lost in pool with no reference.

-1

Because String is immutable so changes will not occur if you will not assign the returned value of function to the string.so in your question assign value of swap function  returned value to s.

s=swap(s, n1, n2) ;then the value of string s will change.

I was also getting the unchanged value when i was writing the program to get some permutations string(Although it is not giving all the permutations but this is for example to answer your question)

Here is a example.

> import java.io.*;  public class MyString { public static void
> main(String []args)throws IOException {  BufferedReader br=new
> BufferedReader(new InputStreamReader(System.in));  String
> s=br.readLine().trim(); int n=0;int k=0;  while(n!=s.length()) {
> while(k<n){  swap(s,k,n); System.out.println(s); swap(s,k,n); k++; }
> n++; } }  public static void swap(String s,int n1,int n2) { char temp;
> temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s);
> sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString();
> } }

but i was not getting the permuted values of the string from above code.So I assigned the returned value of the swap function to the string and got changed values of string. after assigning the returned value i got the permuted values of string.

/import java.util.*; import java.io.*; public class MyString { public static void main(String []args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
String s=br.readLine().trim(); int n=0;int k=0; 
while(n!=s.length()){ while(k<n){ s=swap(s,k,n); 
System.out.println(s); s=swap(s,k,n); k++; } n++; } } 
public static String swap(String s,int n1,int n2){
char temp; temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s); sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString(); return s; } }
0
-1
    public final class String_Test {

    String name;
    List<String> list=new ArrayList<String>();

    public static void main(String[] args) {

        String_Test obj=new String_Test();
        obj.list.add("item");//List will point to a memory unit- i.e will have one Hashcode value #1234

        List<String> list2=obj.list; //lis1 also will point to same #1234

        obj.list.add("new item");//Hashcode of list is not altered- List is mutable, so reference remains same, only value in that memory location changes

        String name2=obj.name="Myname"; // name2 and name will point to same instance of string -Hashcode #5678
        obj.name = "second name";// String is Immutable- New String HAI is created and name will point to this new instance- bcoz of this Hashcode changes here #0089

        System.out.println(obj.list.hashCode());
        System.out.println(list2.hashCode());
        System.out.println(list3.hashCode());

        System.out.println("===========");
        System.out.println(obj.name.hashCode());
        System.out.println(name2.hashCode());
    }
}

Will produce out put something like this

1419358369 1419358369

103056 65078777

Purpose of Immutable object is that its value should not be altered once assigned. It will return new object everytime you try to alter it based on the implementation. Note: Stringbuffer instead of string can be used to avoid this.

To your last question :: u will have one reference , and 2 strings in string pool.. Except the reference will point to m!ss!ss!pp!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.