Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString(),trim() and valueOf()

 
swapna sivaraju
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
swapna sivaraju
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic