Java Program to Check Palindrome String
A string is a palindrome if it reads the same from left to right and from right to left. For example, madam, level, and tattarrattat are palindrome strings, while java is not.
In Java, we can check whether a string is a palindrome in several ways. This tutorial demonstrates two common approaches: reversing the string with StringBuilder and comparing characters from both ends without creating a reversed string. It also shows how to read the string using Scanner and how to perform a case-insensitive palindrome check.
Check Palindrome String in Java using StringBuilder reverse()
A string is a palindrome when it is equal to its reversed value. Java’s StringBuilder class provides the reverse() method, which makes this approach straightforward.
In the following program, the given string is converted to a StringBuilder, reversed, converted back to a String, and compared with the original string using equals().
PalindromeString.java
/**
* Java Program - Check if String is Palindrome
*/
public class PalindromeString {
public static void main(String[] args) {
String str = "tattarrattat";
//reverse the string
String rev = (new StringBuilder(str)).reverse().toString();
//check if str is palindrome
if(str.equals(rev)) {
System.out.println(str+" is Palindrome.");
} else {
System.out.println(str+" is not Palindrome.");
}
}
}
Output
tattarrattat is Palindrome.
Here, the reversed string is also tattarrattat. Therefore, str.equals(rev) evaluates to true.
Check Palindrome String in Java using a for Loop
A palindrome can also be detected without reversing the complete string. Compare the first character with the last character, the second character with the second-last character, and continue toward the middle of the string.
If any pair of characters is different, the string is not a palindrome. Only half of the string needs to be checked because every character in the first half is paired with a corresponding character in the second half.
Palindrome String Algorithm using Character Comparison
We shall implement following algorithm in Java and write a program to check if given string is palindrome.
- Start.
- Take string in str. We need to check if this is palindrome string or not.
- Take a boolean variable isPalindrome to store if the string is palindrome or not. Initialize it with
true. - Initialize variable i with
0. - Check if i is less than half the length of string str. If yes, go to step 6, else go to step 8.
- Check if character in str at index i is equal to that of at
length-1-i. If not set isPalindrome tofalseand go to step 8. - Increment i. Go to step 5.
- Based on the value of isPalindrome, print the result.
- Stop.
PalindromeString.java
/**
* Java Program - Check if String is Palindrome
*/
public class PalindromeString {
public static void main(String[] args) {
String str = "tattarrattat";
boolean isPalindrome = true;
//check if ith character is same from start and end
for(int i=0;i<str.length()/2;i++) {
if(str.charAt(i)!=str.charAt(str.length()-1-i)) {
isPalindrome = false;
break;
}
}
//check if str is palindrome
if(isPalindrome) {
System.out.println(str+" is Palindrome.");
} else {
System.out.println(str+" is not Palindrome.");
}
}
}
Output
tattarrattat is Palindrome.
For an index i, its matching character from the other end is at index str.length() - 1 - i. The loop stops immediately when it finds a mismatch.
Java Palindrome String Program using Scanner
When the string has to be entered at runtime, use Scanner to read the input. The following program checks the input with a left and right index, so it does not use StringBuilder.reverse().
import java.util.Scanner;
public class PalindromeString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
int left = 0;
int right = str.length() - 1;
boolean isPalindrome = true;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if (isPalindrome) {
System.out.println(str + " is Palindrome.");
} else {
System.out.println(str + " is not Palindrome.");
}
scanner.close();
}
}
For example, if the user enters level, the program produces the following result.
Enter a string: level
level is Palindrome.
Check a Palindrome String in Java without using reverse()
If the requirement is to check a palindrome without using an inbuilt reverse operation, the character-comparison approach is suitable. A reusable method can return as soon as it finds two characters that do not match.
public static boolean isPalindrome(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
return false;
}
}
return true;
}
This method returns false on the first mismatch. If all corresponding characters match, it returns true.
Case-Insensitive Palindrome String Check in Java
The previous examples are case-sensitive. Therefore, Madam is not equal to madaM when compared character by character. If uppercase and lowercase letters should be treated as equivalent, normalize the case before checking the string.
public class PalindromeIgnoreCase {
public static void main(String[] args) {
String str = "Madam";
String normalized = str.toLowerCase();
String reversed = new StringBuilder(normalized).reverse().toString();
if (normalized.equals(reversed)) {
System.out.println(str + " is a palindrome ignoring case.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
}
Madam is a palindrome ignoring case.
Palindrome Check that Ignores Spaces and Punctuation
For phrases, the definition of a palindrome often ignores letter case, spaces, and punctuation. One approach is to create a normalized string containing only letters and digits before performing the palindrome test.
public class PalindromePhrase {
public static void main(String[] args) {
String text = "Never odd or even";
String normalized = text.replaceAll("[^A-Za-z0-9]", "")
.toLowerCase();
String reversed = new StringBuilder(normalized).reverse().toString();
System.out.println(normalized.equals(reversed));
}
}
true
After spaces are removed and letters are converted to lowercase, Never odd or even becomes neveroddoreven, which reads the same in both directions.
StringBuilder vs Character Comparison for Java Palindrome Checks
| Approach | How it works | Time complexity | Extra space |
|---|---|---|---|
StringBuilder.reverse() | Creates a reversed version and compares it with the original string | O(n) | O(n) |
| Character comparison | Compares matching characters from the two ends toward the middle | O(n) | O(1) |
Both approaches have linear time complexity. The character-comparison approach uses constant extra space and can stop as soon as a mismatch is found. The StringBuilder approach is often shorter and easier to read when creating a reversed string is acceptable.
Palindrome String Edge Cases in Java
- Empty string: With the character-comparison algorithm, an empty string has no mismatching character and is therefore treated as a palindrome.
- Single character: A string such as
ais a palindrome because it reads the same in either direction. - Case differences:
Levelis not a palindrome with a case-sensitive comparison unless the case is normalized first. - Spaces and punctuation: A phrase such as
Never odd or evenrequires normalization if spaces are to be ignored. - Null reference: Calling methods such as
length()or constructing aStringBuilderwith an unexpectednullvalue can cause an exception. Decide how a reusable palindrome method should handlenullbefore processing it.
Key Points for Checking Palindrome Strings in Java
- Use
StringBuilder.reverse()when you want a concise reverse-and-compare solution. - Use a
forloop or two indexes when you want to check a palindrome without reversing the string. - Compare only up to the middle of the string when checking characters from both ends.
- Use
equals(), rather than==, to compare the contents of JavaStringobjects. - Normalize the text first when the palindrome comparison should ignore case, spaces, or punctuation.
Java Palindrome String Summary
In this Java Tutorial, we have written Java program using different techniques on how to check if given string is a palindrome or not.
TutorialKart.com