Hi, Following code compiles correctly giving output "EQUAL".
public class twocows { public void two() { if("String".replace('R','r') == "String" ) // note this line System.out.println("Equal"); else System.out.println("Not Equal"); } public static void main (String args[]) {
twocows t = new twocows(); t.two();
} } My question is if I replace with following still it give output EQUAL if("String".replace('R','r') == "String".replace('R','r') ) BUT if I write following output is NOT EQUAL... why ? if("String".replace('r','R') == "String".replace('r','R') ) I am confused becoz we are doing similar operation on both the strings... tks, Ashish
Bharatesh H Kakamari
Ranch Hand
Joined: Nov 09, 2000
Posts: 198
posted
0
i) if("String".replace('R','r') == "String".replace('R','r') ) In this line there is no 'R' in the String 'String' Hence replace() returns the same string both the times. But replace() actually returns a new String. ii) if("String".replace('r','R') == "String".replace('r','R') ) In this case the replace() in both expressions returns a new String. Hence == is false. Verify the API with respect to replace() method of String. HTH
N Mukherjee
Ranch Hand
Joined: Jun 08, 2000
Posts: 141
posted
0
Hi Ashish, replace()returns the "same"String object in your first case as there is no "letter" which you want to replace. In the later case, it returns a new object(String). Hence the result. Hope this helps. Read Maha's contributions on java.lang package. Bye NM
"Knowledge is Power"****************<A HREF="http://www.geocities.com/nityananda_mukherjee" TARGET=_blank rel="nofollow">THREAD/SCJP RESOURCES</A>
Ashish Agnihotri
Ranch Hand
Joined: Nov 16, 2000
Posts: 45
posted
0
Tks Bhartesh and Mukherjee absolutely clear now !! Will read Maha's article..!! Ashish