This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stirngs again... why this happens ?

 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tks Bhartesh and Mukherjee
absolutely clear now !! Will read Maha's article..!!
Ashish
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic