• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about StringBuffer

 
Kathy Wang
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,All, I have problem for the following question,could you please kindly help out? Thanks a lot.
my question is why the result of "System.out.println(sb1.equals(sb2)); " is false?
Q 1. 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));
Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar
Correct Answer is a)
 
Guoqiao Sun
Ranch Hand
Posts: 317
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Wang, the reason is that StringBuffer does not override equals method from Object. As a result, equals method applied to two StringBuffer objects has the same effect as that of == applied to two StringBuffer objects.
Hope it helps.
------------------
Guoqiao Sun
Sun Certified Programmer for Java™ 2 Platform
try my mock exam¹² at my homepage.
 
Gurpreet Sachdeva
Ranch Hand
Posts: 90
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Kathy,
It is because StringBuffer use the equals method of the object class.Object class's equals method compares the reference of the two objects.So, the result is false.
Regards
Gurpreet Sachdeva
For Mock Exams, FAQ and some useful information about Bitshift operator, inner classes, garbage collection,etc please visit: http://www.go4java.20m.com
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic