I've recently started using Java, and I'm trying to get a short program that checks for palindromes in words or short sentences. I want to use StringBuilder for the reverse method. My idea was to have one variable from the user entry (that is converted to lower case with spaces and commas removed) , and then another variable to hold the reversed entry, and compare them using .equals. However, the .reverse() method is changing the value of my user entry, and I cannot figure out why. I know about references in Java, but only recently and don't have a full understanding.
Any help would be much appreciated.
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a word or phrase to test for a palindrome: ");
String entry = kb.nextLine();
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);
System.out.println("sbEntry: " + sbEntry);
StringBuilder sbEntryReverse = sbEntry.reverse();
System.out.println("sbEntryReverse: " + sbEntryReverse);
System.out.println("sbEntry: " + sbEntry);
For the word "Dog", this gives the output:
Enter a word or phrase to test for a palindrome:
Dog
sbEntry: dog
sbEntryReverse: god
sbEntry: god
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() );