• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why this prints false?

 
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 893
Tomcat Server Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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'.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Jesper for filling out the important information
reply
    Bookmark Topic Watch Topic
  • New Topic