Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

equals() method in StringBuffer and Float

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I tried out the following code
StringBuffer sb1 = new StringBuffer("xyz");
StringBuffer sb2 = new StringBuffer("xyz");
System.out.println(sb1.equals(sb2));//output is false
Float f1 = new Float("0.9f");
Float f2 = new Float("0.9f");
System.out.println(f1.equals(f2));//output is true
Can anyone explain me exactly what is happening in the above code, as we are using equals()method in both cases...
Why the output is different in both cases...
Cheers
Ravi
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The StringBuffer class does not override the "equals" method, so equality means identity. The two StringBuffer references are not to the same object on the heap, therefore the objects are not "equal".
The Float class overrides the "equals" method. Two float objects are "equal" if the floatToIntBits() method returns the same int value for each. Since the two Float objects are created with identical constructor calls, they pass the test.
 
permaculture is giving a gift to your future self. After reading this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic