GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toString(),trim() and valueOf() 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 "toString(),trim() and valueOf()" Watch "toString(),trim() and valueOf()" New topic
Author

toString(),trim() and valueOf()

swapna sivaraju
Ranch Hand

Joined: Jan 18, 2002
Posts: 75
Hi,
I need some help regarding this..

1. if("s".toString()=="s")
System.out.println("==");
2. if(String.valueOf('s")=="s")
System.out.println("==");
3.if(" s ".trim()=="s")
System.out.println("==");
1 and 2 print "==" but 3. doesnot....
But i thought all three shouldnot print "=="...as
all these are evaluated at runtime and all of methods(toString(),trim() ,valueOf()) create new String objects so for these codes the equality is checking there refrences rather than their values....thats what i think..am i correct???

DOes the result mean that in 1 and 2
toString() and valueof() are creating anonymous
strings which are referencing the string object "s".??? ....clarify me.
thanks
Swapna


SCPJ2
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
swapna
For the first case:
if("s".toString()=="s")
System.out.println("==");
The toString() method in the String class returns the same string - it returns itself, so == will be true.
The second case, you have a typo in your post, I am assuming it should be:
if(String.valueOf("s")=="s")
System.out.println("==");
In this case what is happening is that you are calling the Object.toString() method, in this case because the Object is a string you get the String.toString() method which returns itself - see explaination #1.
Your third example:
if(" s ".trim()=="s")
System.out.println
The trim() method returns a new String with the white space removed so the == method will return false but equals() would return true.
You can find all of this in the SDK API
hope that helps


Dave
swapna sivaraju
Ranch Hand

Joined: Jan 18, 2002
Posts: 75
Thanks Dave..
I also read the same line..." calling String.valueOf(Object o) is equal to calling
Object.toString()" in Khalid Mughal but still
got confused by the fact that when trim() is creating
a new object then why not toString() and valueOf()..
anyways i got it now....
thanks
swapna
Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
Originally posted by Dave Vick:

Your third example:
if(" s ".trim()=="s")
System.out.println
The trim() method returns a new String with the white space removed so the == method will return false but equals() would return true.

So what would happen if you didn't have extra spaces on the end. Would it create a new instance then even though they are equal?
-Dale


By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
 
GeeCON Prague 2014
 
subject: toString(),trim() and valueOf()