• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Code Concepts

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone plz explain the output of...
StringBuffer sb1 = new StringBuffer("goodday");
StringBuffer sb2= new StringBuffer("goodday");
String ss1 = "goodday";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("puffdar".substring(3));
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I hope you know why == returns false. It is just doing reference comparison on two distinct objects.
Unike String, StringBuffer does not override the equals() method in the Object class. Hence, here equals() is the same as == ie., reference comparison, which returns false in our example.
Hope this helps,
Ajith
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

1. StringBuffer sb1 = new StringBuffer("goodday");
2. StringBuffer sb2= new StringBuffer("goodday");
3. String ss1 = "goodday";
4. System.out.println(sb1==sb2);
5. System.out.println(sb1.equals(sb2));
6. System.out.println(sb1.equals(ss1));
7. System.out.println("puffdar".substring(3));

Line 4 will be false for obvious reasons, sb1 and sb2 are different objects.
Line 5 will be false. StringBuffer class does not override the equals method. So you only have the default method in Object which does nothing more than see if the two references are the same (which happens to be the same as == ).
Line 6 will print false because of different objects.
Line 7 will print "fdar" (without the quotes). The method prints the rest of the string starting the index position specified (remember the index starts at 0).
Hope this helps
Ajay Kumar
 
You save more money with a clothesline than dozens of light bulb purchases. Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic