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

Why this prints false?

pradeep singh
Ranch Hand

Joined: Oct 23, 2007
Posts: 339
what will be the output of the following code?


Byte b1=new Byte("127");
if(b1.toString()==b1.toString())
System.out.println("true");
else
System.out.println("false");


a>compilation error
b>prints "true"
c>prints"false"

answer is given: false.
My question is Why this prints false?


SCJP 5.0(75%), SCWCD 5.0(88%)
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
You could check the api of the Byte class


Byte


There I have read that to Byte toString() behaves exactly like the static method of the Byte toString() which creates a new String object with represents the value of the Byte. So there a 2 new String objects created.


Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3355

Thanks for the link Campbell.

Just to add on top of what CR said, no matter what, you invoke the toString() method twice on both sides of the == operator. That gets you a brand new String object at each place.

So, they are NOT equal and thus the result is 'false'.


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14432
    
  23

To add to what Remko and Raghavan said, if you use the == operator on objects, you are not comparing the contents of the objects; you are only checking if the two expressions on both sides of the == refer to the exact same object.

If you have two different String objects, == will return false (no matter what those String objects contain).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3355

Thank you Jesper for filling out the important information
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why this prints false?