• 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

comparison

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class test
{
public static void main(String args[]){
Byte b1=new Byte("127");
if(b1.toString()==b1.toString()) System.out.println("True");
else
System.out.println("False");
}
};
why this fragment prints false ?
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My guess is that b1.toString() and b2.toString() return two different String objects.
Khaled says " Each wrapper class overrides the toString() method. The overriding method returns a String object representing the primitive value. "
In this case, b1.toString() and b2.toString(), maybe returning two objects, each occupying a different memory location, but having the same value.
The operator == is comparing for object equality, and not value equality. On the other hand,
b1.toString().equals(b2.toString())
returns true.
Please correct me if my understanding is wrong.
 
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi
it returns false because like sharada said returns two new String objects and since == checks the refernces this returns false
also note that if the same code was replaced with Boolean or String objects instead of Byte or any other wrapper classes then the value printed would be false .... this is because in both these cases the Strings are maintained in the Constants pool and share the same String object ... hence would return TRUE
hope that helps
Samith.P.Nambiar
-----------------------------
harder u try luckier u get
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic