File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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");

a>compilation error
b>prints "true"

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


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: 3381

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: 15081

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: 3381

Thank you Jesper for filling out the important information
wood burning stoves
subject: Why this prints false?
It's not a secret anymore!