• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this prints false?

 
pradeep singh
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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'.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Jesper for filling out the important information
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic