Basically, == is checking reference identity (do the references refer to exactly the same String object in the heap?) In this case you have different dynamically generated String objects, so the == test will return false.
All code in my posts, unless a source is explicitly mentioned, is my own.
If you look into the replace method you find this line to create a new String:
And as we know, if the new keyword is used, a new object is created even if this string literal is already there.
And if a new string object is created, your code prints a not equal.
vikky.ag agrawal wrote:String object remains in heap and if any string present there then that string refers to that string
Well you need to understand that there is a pool of strings maintained by the JVM for faster String processing. It would be worth to give this article a reading...
Bottom line is that every time you mutate a String object, you get a brand new String object which is not same any other String objects created earlier (even if the content is same). So here s3 is new object and so is s4. That's why == comparison shows as false.
Santhosh Kumar wrote:Bottom line is that every time you mutate a String object, you get a brand new String object which is not same any other String objects created earlier (even if the content is same). So here s3 is new object and so is s4. That's why == comparison shows as false.