aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Stirngs again... why this happens ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Stirngs again... why this happens ?" Watch "Stirngs again... why this happens ?" New topic
Author

Stirngs again... why this happens ?

Ashish Agnihotri
Ranch Hand

Joined: Nov 16, 2000
Posts: 45
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

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
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

Tks Bhartesh and Mukherjee
absolutely clear now !! Will read Maha's article..!!
Ashish
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Stirngs again... why this happens ?