aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Interesting Question 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 "Interesting Question" Watch "Interesting Question" New topic
Author

Interesting Question

Sagar Bilgi
Ranch Hand

Joined: Apr 26, 2001
Posts: 37
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

Joined: Sep 08, 2000
Posts: 61
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


----------------------<br />regards.<br /><a href="http://www.mantrotech.com/editors/gaurav_mantro.asp" target="_blank" rel="nofollow">Gaurav Mantro</a><br /><a href="http://www.mantrotech.com/technology/java/index.asp" target="_blank" rel="nofollow">Java Information Portal</a> - <a href="http://www.mantrotech.com/technology/java/index.asp" target="_blank" rel="nofollow">http://java.mantrotech.com</a>
Sagar Bilgi
Ranch Hand

Joined: Apr 26, 2001
Posts: 37
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

Joined: Jan 26, 2001
Posts: 158
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

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interesting Question