• 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

Mock Question on StringBuffer

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please help me about this mock question.
public class StringBufferTest {
public static void main(String args[]) {
StringBuffer sb1 = new StringBuffer("Prakash");
StringBuffer sb2 = new StringBuffer("Prakash");
if(sb1.equals(sb2)) System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
How come the answer is "Not Equal". I have coimpiled and tested it also.
I know that equals compares content but in this case why its not doing that.
 
Desperado
Posts: 3226
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, <CODE>equals()</CODE> doesn't always compare content. Like in the <CODE>StringBuffer</CODE> class. It does compare content for <CODE>String</CODE> buy not for <CODE>StringBuffer</CODE>.
This can be found out by reading the Java API and looking to see if the particular class overrides <CODE>equals()</CODE>.
You'll see that <CODE>String</CODE> does and <CODE>StringBuffer</CODE> doesn't. So the only way two <CODE>StringBuffer</CODE>s will compare equally is if they both denote the same <CODE>StringBuffer</CODE> object.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String and Wrapper class overrides equals() from the Object. Both the cases equals method compares the content and which is not true for the other classes.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much for your help.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic