• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confused with String Equality

 
geeta vemula
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got these from

http://www.angelfire.com/or/abhilash/quiz/quiz4.html

1. Read this piece of code carefully

if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers

the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error
Ans b


2. Read this piece of code carefully

if("String".replace('T','t') == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers

the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error
Ans a

3. Read this piece of code carefully

if("String".replace('t','t') == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers

the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error
Ans a

When it gives equal and when not? very much confused with this. Kindly help me.

Thanks
Geeta Vemula
 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The replace method returns a new string object IF AND ONLY IF there is any change in the actually string.

Look at the replace method implementation.

[ December 31, 2008: Message edited by: James Tharakan ]
 
Vinod Kumar Kommineni
Ranch Hand
Posts: 54
Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Geetha according to what James had posted I feel that in 2nd and 3rd code blocks there is no change in the String
2nd -because T is not present in String at all,
3rd- since old and new variable are equal.

But any comparison of String's with == is not encouraged instead if you use string1.equals(string2) it will give true results.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic