This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
The code will compile and print "Equal". The code will compile and print "Not Equal". The code will cause a compiler error. The code will compile but will throw runtime exception.
The code above compare two reference to the different String object. Pls remember String is immutable Class, So "String".replace('g','G') will result in creating reference to a new String object with value of "StringG". Two times excution will create two different reference, so the result of comparison is the false. Hope explanation makes sense.
V Gala
Ranch Hand
Joined: Aug 06, 2007
Posts: 113
posted
0
thanks
("StrinG".replace('g','G') == "StrinG".replace('g','G')) this is giving true since StrinG is not replace please correct me if I am wrong
The second replace doesn't make reference to the first reference either?
Haibo Jia
Greenhorn
Joined: Aug 22, 2007
Posts: 6
posted
0
Hi Alexsandra,
The two replace methods will create two objects refered by 2 ref, so compansion of ref result in false. Thax.
dhwani mathur
Ranch Hand
Joined: May 08, 2007
Posts: 621
posted
0
hi Haibo Jia !!
As you said it will return false so i got the point, but why in the post by V Gala as shown below it is said it returns true........although both the statements are same?Is it i am making some mistake ?
String.replace() method returns a new object if any change happens, otherwise it returns the same object as it is.
Originally posted by dhwani mathur:
("StrinG".replace('g','G') == "StrinG".replace('g','G')) this is giving true since StrinG is not replace please correct me if I am wrong
So, you are absolutely right. [ August 24, 2007: Message edited by: Al Mamun ]
MooN
Radha Kamesh
Ranch Hand
Joined: May 19, 2007
Posts: 33
posted
0
Hi,
i was going through the above discussion when i stumbled upon this piece of code... now i'm confused...
i ran this piece of code:
OUTPUT:
arit amit arit arit false true
Going by the above discussion, in this code , line 4 creates a new String Object with value 'arit'. Now when line 5 is executed shouldn't s3 point to the newly created 'arit' object? Wont it see in the String pool and find that such a String already exists and point the new references s3 and s4 to it?
But why am i getting false as the result of line 8? i'm confused ... please explain...
Thanks in advance Radha [ August 25, 2007: Message edited by: Radhika ]
V Gala
Ranch Hand
Joined: Aug 06, 2007
Posts: 113
posted
0
Hi String s1 = new String("amit"); String s2 = "amit"; String s3 = new String("amit"); if(s1==s2) ans is false if(s1==s3) ans is false whwn we write s1.replace('m','r') it is eqivalent to String var= new String("arit");