my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes confused with String Equality Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "confused with String Equality" Watch "confused with String Equality" New topic
Author

confused with String Equality

geeta vemula
Ranch Hand

Joined: Jul 18, 2008
Posts: 208
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

Joined: Aug 29, 2008
Posts: 580

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 ]

SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Vinod Kumar Kommineni
Ranch Hand

Joined: Jun 12, 2008
Posts: 54

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.


Regards
vinod SCJP 6.0
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: confused with String Equality