This week's book giveaway is in the HTML Pages with CSS and JavaScript forum.
We're giving away four copies of Testing JavaScript Applications and have Lucas da Costa on-line!
See this thread for details.
Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript 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

String Buffer

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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));
a) false
false
false
dar
b) false
true
false
Poddar
c) compiler error
d) true
true
false
dar
The given answer is a.
Doesn't StringBuffer don't have "==" or "equals()".....?
Thanks
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== operator compares the references
In the given program, sb1 and sb2 are referring to different objects.
So, sb1 == sb2 is false.
String and StrinBuffer both have equals() method that compare two encapsulated strings.
The StringBuffer class inherits its equals() method from Object, so the method does not perform expected behavior, which would be chracter by character comparison.
And you cannot compare String to StrinBuffer.

If I am wrong, anyone can correct me.....
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

-> sb1 == sb2 is false Since the object references will be will be compared
-> sb1.equals(sb2) is false since StringBuffer does not have an equals method so the Object's equals method will be called (which does a comparision of the references)
-> sb1.equals(ss1) is false. for the same reason as sb1.equals(sb2)
-> "Poddar".subString(3) will give you "dar" provided you spell subString(3) with a lowercase 's' as substring(3).
 
The fastest and most reliable components of any system are those that are not there. Tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic