This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String Question" Watch "String Question" New topic
Author

String Question

mansoor iqbal
Ranch Hand

Joined: Aug 14, 2000
Posts: 91
just when i thought i knew it all:

String str="String";
if("String".toString() == str.toString())
System.out.println("Equal");
else
System.out.println("Not Equal");
prints equal......why???
if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Equal");
else
System.out.println("Not Equal");
prints not equal.....why?
if("String".replace('t','t') == "String".replace('t','t'))
System.out.println("Equal");
else
System.out.println("Not Equal");
prints equal.....why?
thanks in advance

rajashree ghatak
Ranch Hand

Joined: Mar 10, 2001
Posts: 151
in the first piece of code following takes place behind the scene:
String str="String"; //creates a String object.
When u use "String".toString(),no new object is being created,instead String pool is used.So both refer to the same instance of String.Hence == returns Equal.
in the second piece of code:
2 new String objects are creatd that contain the modifications that take place because of replace operation of String.Hence == returns Not Equal.
i am not sure of the third code.
lee dalais
Ranch Hand

Joined: Feb 28, 2001
Posts: 67
hi mansoor
this is what i think:
1.
String str="String"; //gets put into a string pool
str.toString() //returns 'String', but 'String' is already in string pool
"String".toString() // returns 'String', but 'String' is already in string pool
so they both have reference to the same string, so '==' returns true.
2.it seems that with this, both statements
"String".replace('g','G') check the string pool and find that there is no matching string, so they both return different references. so unequal.
if u said ("String".replace('g','G')).intern() to both it would return equal as they would both be put in the string pool but the strings are the same so they would both refer to onw string so same reference.
3.with this, both statements
("String".replace('t','t') check the string pool and find a matching string so they both return the same reference, so equal
[This message has been edited by lee dalais (edited March 30, 2001).]
 
wood burning stoves
 
subject: String Question
 
Similar Threads
General problems..
Doubts in Strings
Different behaviour with string objects
About String
Strings