Q: How to compare two StringBuffer Objects using .equals() method? The following code did not work. Can anyone tell me what's wrong with the following code. Logically it should work...
package assignments;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IsPalindrome {
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(
                                      new InputStreamReader(System.in));
    System.out.println("Enter a Word:");
    StringBuffer sb1 = new StringBuffer(br.readLine());
    StringBuffer sb2 = new StringBuffer(sb1);
    sb1.reverse();

    if(sb2.equals(sb1))
        System.out.println("Palindrome");
    else
        System.out.println("Not a Palindrome");
}
}


A: In StringBuffer class equals method is not overriden as in String class. In StringBuffer it just looks whether the references are the same.
 Therefore you first need to convert that to a String and then use equals method.
So Try
sb1.toString().equals(sb2.toString());


A: Try
sb1.toString().equals(sb2.toString());

because StringBuffer#toString method returns the String value of the data stored inside the buffer:

Returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.


A: You can write
System.out.println("Enter a line:");
String line = br.readLine().replace(" ", ""); // palindromes can have spaces
String reverse = new StringBuilder(sb1).reverse().toString();

if(line.equals(reverse))
    System.out.print("Not a ");
System.out.println("Palindrome");

