Why So Serious :
I was trying to check that a String is a palindrome using StringBuilder
and reverse()
. For a word with no symmetry like "chan" it correctly returns false
, but it also returns false
for genuine palindromes like "madam".
Code:
StringBuilder str = new StringBuilder("madam");
StringBuilder str2 = new StringBuilder(str);
boolean res = str2.equals(str.reverse().toString().trim());
System.out.println(str + " " + str2);
System.out.println(res);
Output:
madam madam
false
I am running Eclipse Neon with Java 8.
Eran :
str.reverse().toString().trim()
is a String
, so it cannot be equal to a StringBuilder
.
Try to compare 2 String
s instead:
boolean res=str2.toString().equals(str.reverse().toString().trim());