This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interesting Question

 
Sagar Bilgi
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Byte b1 = new Byte("127");
if(b1.toString() == b1.toString())
System.out.println("True");
else
System.out.println("False");
WHy does this print FALSE??
Please answer!!!
 
Gaurav Mantro
Ranch Hand
Posts: 61
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Expression b1.toString() == b1.toString() is false because you are comparing object references. If you want to compare contents of the object then you should use equals() operator. Expression b1.toString().equals(b1.toString()) will return true.
hope it helps.
cheers
Gaurav Mantro
------------------
http://www.mantrotech.com
 
Sagar Bilgi
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gaurav Mantro:
Expression [b]b1.toString() == b1.toString() is false because you are comparing object references. If you want to compare contents of the object then you should use equals() operator. Expression b1.toString().equals(b1.toString()) will return true.
hope it helps.
cheers
Gaurav Mantro
[/B]

Yeah gaurav, I know that but arent we comparing the same object?? ie b1
..
 
Jyotsna Clarkin
Ranch Hand
Posts: 158
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sagar Bilgi:
Yeah gaurav, I know that but arent we comparing the same object?? ie b1 ..

No, you are not comparing the same object.
The toString() method is overriden in Byte class to return a new String.
So the if clause
if(b1.toString() == b1.toString())

creates two differentobjects because toString() is called twice.
Hence == will return False.
The contents of the objects are the same though.
Hence equals() will return true.
regards,
Jyotsna
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't post the same question in multiple forums - it wastes our time to reply to questions when there's already a perfectly good answer in another forum. I'm closing this thread - see duplicate in JiG Beginner.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic