This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Buffer

 
Rajiv Ranjan
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Guys,
Is there any particular reason why method equals is not overridden in StringBuffer class?
If you test this piece of code :
public class TestClass
{
public static void main(String Args[])
{
StringBuffer sb1 = new StringBuffer("String");
StringBuffer sb2 = new StringBuffer("String");
if(sb1.equals(sb2))
{
//lots of code
}
}
}

The author of the question said "Line marked with lots of code is never reached" and he is correct (as I modified and tested the code).
 
ming fan
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to RHE JAVA 2 Study Guide, Chapter 8, java.lang and java.util Packages, StringBuffer inherits from the Object equals method, so it doesn't give you what you expected.
 
Suresh Selvaraj
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The equals() method belongs to java.lang.Object and hence any class can override the equals() method. Both String and StringBuffer classes have equals() method.
As per your code,
StringBuffer sb1 = new StringBuffer("String");
StringBuffer sb2 = new StringBuffer("String");
sb1.equals(sb2)checks for the memory address and since sb1 and sb2 refer to two new objects, their memory address is different and hence sb1.equals(sb2) return False.
The following check on StringBuffers will also return False. if(sb1==sb2), returns false.
The contents of StringBuffers sb1 and sb2 can be checked by equals() method like this...
sb1.toString().equals(sb2.toString()) - This check will return True.
You may try the code mentioned below.
public class StringBufferTest
{
public static void main(String Args[])
{
StringBuffer sb1 = new StringBuffer("String");
StringBuffer sb2 = new StringBuffer("String");
if(sb1.equals(sb2))
{
System.out.println("EQUALS");
}
else
{
System.out.println("NOT EQUALS");
}

if(sb1.toString().equals(sb2.toString()))
{
System.out.println("toString EQUALS");
}
else
{
System.out.println("toString NOT EQUALS");
}
if(sb1==sb2)
{
System.out.println(" == EQUALS");
}
else
{
System.out.println("== NOT EQUALS");
}
}
}
The Output of the above code is :
NOT EQUALS
toString EQUALS
== NOT EQUALS
- Suresh Selvaraj
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic