This line is comparing str2
, an instance of StringBuilder
, with an instance of String
:
boolean res = str2.equals(str.reverse().toString().trim());
It's common for objects of two different classes to always say they are not equal, because they aren't generally programmed to know how to examine the contents of different types of object. (There are some cases where it's specified to work, such as different implementations of java.util.List
.)
In this case, it's even worse, because StringBuilder
does not override the equals
method at all. If you check the class documentation, you'll see equals
listed as one of the methods inherited from Object
. So it will return true
only when passed the same object instance; it never compares content.
StringBuilder sb1 = new StringBuilder("abc");
StringBuilder sb2 = new StringBuilder(sb1);
System.out.println(sb1.equals(sb1)); // true; same object
System.out.println(sb1.equals(sb2)); // false; different objects (same content)
So you cannot compare any StringBuilder
instances this way. To do the comparison, convert your reversed result back to a plain String
:
String input = "madam";
input = input.trim();
String reversed = new StringBuilder(input).reverse().toString();
System.out.println(input + " " + reversed);
System.out.println(input.equals(reversed));
Note: If you want to trim()
a user input, do it at the earliest moment. If you trim after reversal, you will have to trim both halves of the comparison.