This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Strings...  RSS feed

 
simpu ch
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello evryone,
i've been going thru poddar's q's on strings and the very first one caught me(lacking precise knowledge about strings and stringbuffers..)
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)
for this ," System.out.println(sb1.equals(sb2)); " ...my thinking is that...
since equals compares deeply(or the strings and not references),the o/p should be true.

same with the " System.out.println(sb1.equals(ss1)); " the o/p should be true.
I couldn't reason my thinking with the given answer..

plz..somone give some explanation



Thanks,
simpu.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simpu,

The equals method of StringBuffer does not override Object.equals(); so StringBuffer.equals() is really no different than the equality operator, ==.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If anybody is wondering how Dan could possibly know that StringBuffer doesn't override the equals method, you might like to familiarize yourself with the J2SE API documentation. The StringBuffer class documentation (as well as the documentation for other classes) lists what methods the class defines, and what methods it inherits.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!