Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Buffer

 
devi nachimuthu
Greenhorn
Posts: 10
  • 0
  • 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
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • 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.....
 
Sachin Kombrabail
Greenhorn
Posts: 14
  • 0
  • 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).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic