As you probably know, comparing Strings with == yields true only when both are the same String instance. When you have duplicate String literals in your code, they are resolved to a single String instance. That is the case for the various "String" in that code, they are the same instance. In the first piece of code, method replace() returns a new String instance that is the result of applying that replacement on the original instance. You have two calls to replace() on the same original instance, yielding 2 new String instances with the results. The results are "equal" but not the same instance, therefore == yields false. In the second piece of code, replace() finds nothing to replace, and so it returns the original String instance, not a new one. Both results are then the same original instance, so == yields true. In the last piece, replace() returns a new instance. The literal "STring" and the result are equal() but they're separate instances. Therefore == yields false. If it still doesn't make sense to you, make sure to learn how Java works with Strings in general, literal Strings in particular, and the operator ==.
1. first operand "String".replace('g','G') == --> This will create new Object ie "StrinG" 2. second operand "String".replace('g','G') --> This will also create object ie "StrinG" My doubt is the object created in line 2 allready exist in the pool.In that case will it create a new object
Ankith, Strings resolved at runtime and Strings explicitly created with new (even if the initial value is a literal that is in the pool) are not automatically interned (mapped to the pool). They are distinct instances, unless the intern() method is called. Method replace() is probably using new behind the scenes!
Thanks greg for the explaination... this means replace function make the new instance always if changes are there & what about rest of the functions like substring,concat etc. Do they also behave in same manner. Also intern() method is new thing for me...can please tell me what is it...
I think it's pretty safe to say that substring and such methods create new instances too, you can make a simple test to compare the results (with ==) against a String literal that has the same contents. The intern() method gives you a reference to the String pool instance that is equal() to your String. I don't remember what happens if it doesn't exist, I have never actually used it. But look it up, you will quickly find more valuable information than anything I can say here