You cannot compare sbEntry
and sbEntryReverse
because sbEntry.reverse()
changes the contents of the StringBuffer
to which sbEntry
refers. Unlike methods that operate on immutable String
objects, StringBuffer
methods like reverse()
alter the character buffer inside the StringBuffer
object. StringBuffer
objects are mutable while String
objects are not.
Instead, you need to compare the final contents of the StringBuffer
(sbEntry
or sbEntryReverse
) with the original input string, entryFinal
:
String entryLower = entry.toLowerCase();
String entryNoSpace = entryLower.replace(" ", "");
String entryFinal = entryNoSpace.replace(",", "");
//Convert String to StringBuilder to use reverse method
StringBuilder sbEntry = new StringBuilder(entryFinal);
StringBuilder sbEntryReverse = sbEntry.reverse();
boolean isPalindrome = entryFinal.equals( sbEntryReverse.toString() );