The String object is immutable.
String str = "ObjectOne"+"ObjectTwo"; is same as String str = "ObjectOneObjectTwo";
By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind: โIf String is immutable, then how can I change the contents of an object when I want?โ Well, more precisely, its not the same String object that reflects the changes you make. For internal changes, a new String object is created.
So, suppose you declare a String object:
String myString = "Hello";
Then you want to add the "Guest" to the same Line. What are you doing?
myString = myString + " Guest";
When you print the contents of myString, the output will be "Hello Guest". Although we used the same object (myString), a new object was created inside the process. So the mystic will refer to "Hello Guest." Hello link lost.
String s1 = "hello"; //case 1 String s2 = "hello"; //case 2
In case 1, literally s1 is created and stored in the pool. But in case 2, the letter s2 refers to s1; instead, it will not create a new one.
if (s1 == s2) System.out.println ("equal"); // Print Equals
String s= "abc"; //initaly s refers to abc String s2 =s; //s2 also refers to abc s=s.concat("def"); // s refers to abcdef. s no longer refers to abc.

source share