posted 23 years ago
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
Suresh Selvaraj, (author of JQuiz)<br />SCJP2<br /><a href="http://www.decontconsulting.com" target="_blank" rel="nofollow">www.decontconsulting.com</a>