Originally posted by gkcom gk:
String s1 = new String("Amit");
String s2 = s1.replace('m','r');
String s3 = "Arit";
String s4 = "Arit";
1.System.out.println(s2==s3)-> false
2.System.out.println(s3==s4)-> true
Why 1. is false , because s2 and s3 both referring to "Arit".If it is different object reference, then why 2. is true . s3 and s4 too are different reference .
Please explain me in detail. What is the difference between these two ways of creating String
String s3 = "Amit"; and String s1 = new String("Amit"); Both are same object or different object,both referring to same refernce or different.
Thanks
At compile time
Java strings literals are stored in the string pool. There can be only one reference to the same string in the string pool.
The statement String s3 = "Arit" puts the string literal "Arit" in the pool. String s4 is then given a reference to the same object as it is already contained in the string pool.
However any for Strings declared using the String s =new String("xyz) constructor or any of the String methods that return a String such as trim() or replace() a new string object is created and placed on the heap and not placed in the string pool.
So if the lines were changed too
String s3 = new String("Arit");
String s4 = new String("Arit");
This would create two new string objects in the heap and so s3==s4 would be false.