Determine Palindromes using Java

This Java tutorial shows how to determine if a string is a palindrome using Java.

First, what is a palindrome. From Wikipedia:

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.

In a previous tutorial, we showed how to reverse a string. This tutorial takes it the next step and checks to see if the string is a palindrome.

To determine if it is a palindrome, we have added an extra line to compare the reverse string is the same as the original string. If it the same, it is a palindrome.
//Original String String
originalString = "Radar";

//Create a StringBuffer from the original string
StringBuffer buffer = new StringBuffer(originalString);

//Reverse the contents of the StringBuffer
buffer = buffer.reverse();

//Convert the StringBuffer back to a String
String reverseString = buffer.toString();

//Determine if the string is a palindrome
boolean isPalindrome = originalString.equalsIgnoreCase(reverse);

//Print the original and if it is a palindrome
System.out.println("palindrome: " + originalString + " - " + isPalindrome);

Below is the output from the sample code above:
palindrome: Radar - true

Some definitions of palindromes allow for the exclusion of spaces and punctuation. If you want to exclude spaces and punctuation, you can replace all spaces and punctuation before creating the StringBuffer.

//Replace spaces and punctuation
originalString = originalString.replaceAll("[ ,.?!]", "");


Post a Comment