0

As String is a immutable object, we cannot change a string. But after running this code, the value of the string will be "HelloWorld". Can anybody please explain the reason for it?

class StringTest
{
    public static void main(String args[])
    {
        String str1="Hello";
        String str2="World";
        str1=str1+str2;
        System.out.println(str1);
    }
}
Reto Koradi
  • 53,228
  • 8
  • 93
  • 133
  • Because str1+str2 is creating a new String, which contains "Hello World" and you assign this String to str1. You could also write: String str3= str1 + str2; Would be more clear what happens. – Thallius Sep 30 '14 at 06:09
  • Could you add the "Java" tag to your question ? – personne3000 Sep 30 '14 at 06:14

3 Answers3

1

When you run this code, you are creating a new String object and making str1 pointing to the new String.

You are not changing str1 value, you are just creating a new one, and deleting (automatically using GC) the old one. In other words, str1 is referencing a different object.

zozelfelfo
  • 3,776
  • 2
  • 21
  • 35
1

str1 and str2 are references to String objects, not string objects. When you write:

str1=str1+str2;

str1 will reference a new string object that was created by calculating str1+str2.

In fact, you can try:

String str1 = new String("Hello");
String str2 = new String("World");
String str4 = new String("Hello");

// False: content ("Hello") is the same, but the object instance is different
System.out.println(str1 == str4); 

String str3 = str1;

// True: refers to the same object
System.out.println(str1 == str3); 

str1 = str1 + str2;

// False: a new object has been created and put in str1
System.out.println(str1 == str3); 

The String str1 = new String("Hello") notation is essentially the same as writing String str1 = "Hello", except that it bypasses some optimizations that could make this sample not work as intended (see comments).

personne3000
  • 1,780
  • 3
  • 16
  • 27
  • 1
    These statement could not be 100% true, due to Java String pool. http://stackoverflow.com/questions/2486191/java-string-pool. You should do `new String("Hello")` and so on to make this work 100% – zozelfelfo Sep 30 '14 at 06:16
1

When you perform 'str1+str2' you are basically creating new string object and assigning its reference to str1 . In this case reference to "Hello" has been replaced by the reference of new string created.

Atul Sharma
  • 718
  • 4
  • 11