• 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

Equality question

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a question and the answer .
Q 1. What is the output of the following
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));
Ans:
a) false
false
false
dar

I understood why everything else is false except the second false.
Here 2 stringbuffers are being compared using equals method and they contain the same string "Amit". Why is it giving false ?
Thanks,
Srini
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I might be wrong on this, but the String class .equals() compares the contents of 2 strings. I' am not sure if this holds true for the StringBuffer class. Is essence it is really comparing 2 Objects not 2 String Objects, so this example is using the Object .equals() and not the String .equals().
Please correct me if I am wrong.
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark is right. StringBuffer does NOT override the equals
method. So it just inherites the equals method from
Object class.
It just is the same as ==. So it returns false!
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
Mark is correct..When you are using the equals() on 2 StringBuffers which are same , you still get a false value is because of the following (I guess...):
- The StringBuffer class does not override the equals() provided by the Object class. Hence you are actually calling the Object's version of equals(); and this version does a "shallow" comparision i.e. it does a "==" comparision and hence it returns
a false.
Hope the above helps.
Fazal
 
srini bhav
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all of you.
Srinivas
 
The moth suit and wings road is much more exciting than taxes. Or this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic