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

Code Concepts

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic