Palindrome strings are strings that look the same no matter whether you read them from left to right or right to left. For example, “eye”, “noon”, and “madam” are palindrome strings while “Java”, “javabeat”, and “net” are not palindromes. Other than strings, a number, phrase/sentence can also be a palindrome. If you’re a beginner, creating a Java program that checks palindromes is a good practice to boost your Java (programming) skills.
This guide demonstrates several methods of checking a palindrome string in Java.
How to Check Palindrome Strings in Java
To check palindrome strings in Java, you can use one of the following methods:
- Method 1: Check Palindrome String Using StringBuffer Class
- Method 2: Check Palindrome String Using for Loop (Naive Approach)
- Method 3: Check Palindrome String Using Two Pointers (Optimized Approach)
- Method 4: Check Palindrome String Using Recursion
- How to Check Palindrome Numbers in Java
Let’s begin with the StringBuffer approach.
Method 1: Check Palindrome String Using StringBuffer Class
StringBuffer is a built-in Java class that allows you to create mutable/modifiable string objects. This class offers several constructors and inbuilt methods to execute various string operations. For instance, in the below code, we use the StringBuffer() constructor to create a string buffer with the given string. Also, we use the reverse() method alongside the StringBuffer() constructor to reverse the given string. After this, we use the equals() method in the if-else statement to check if the input and the reversed strings are equal or not. If yes! This means the given string is palindrome else, not a palindrome string:
import java.util.Scanner;
public class PalindromeExample { //custom method to find palindrome
public static void checkPalindrome(String inputStr) {
String reverse = new StringBuffer(inputStr).reverse().toString();
if (inputStr.equals(reverse)) {
System.out.println("The Given String is Palindrome");
} else {
System.out.println("The Given String is Not a Palindrome");
}
} //the main() method
public static void main(String[] args) {
System.out.println("Enter a String to Check for Palindrome");
Scanner scanInput = new Scanner(System.in);
String inputStr = scanInput.next();
checkPalindrome(inputStr);
scanInput.close();
}
}
In the main() method, we use the Scanner class to ask the user to input a string. After this, we invoke the user-defined checkPalindrome() method with the user-entered string to check whether it is a palindrome or not:
The user enters “bob”, which is a palindrome string, so the output is retrieved accordingly.
Method 2: Check Palindrome String Using for Loop (Naive Approach)
Java also allows us to use loops to check if a string is palindrome or not. For instance, in the following code, we create a user-defined “checkPalindrome()” method that uses a for loop to check if the given string is palindrome or not:
import java.util.Scanner;
public class PalindromeExample {
public static boolean checkPalindrome(String inputStr) {
String reverseString = "";
boolean result = false;
int strLength = inputStr.length();
//Reversing the Actual String
for (int i = strLength - 1; i >= 0; i--) {
reverseString = reverseString + inputStr.charAt(i);
}
//Compare Actual String with Reversed string
if (inputStr.equals(reverseString)) {
result = true;
}
return result;
}
//the main() method
public static void main(String[] args) {
System.out.println("Enter a String to Check for Palindrome");
Scanner scanInput = new Scanner(System.in);
String inputStr = scanInput.next();
inputStr = inputStr.toLowerCase();
boolean isPalindrome = checkPalindrome(inputStr);
System.out.println("The Given String is Palindrome ==> " + isPalindrome);
scanInput.close();
}
}
In the checkPalindrome() method,
- First, we create a string-type variable and initialize it with “” (we will store the reversed string in this variable).
- Also, we create a boolean variable and initialize it with false.
- Up next, we use the for loop to iterate the given string from the last index to the initial index. Within the loop’s body, we use the charAt() method to get a character from the current index and store it in the “reverseString” variable. This way, the given string will be reversed completely.
- After this, we use the equals() method with if-else to compare the actual and reversed strings and return true if both the strings are equal.
- Finally, we invoke the user-defined checkPalindrome() method with the input string and print the result accordingly:
Method 3: Check Palindrome String Using Two Pointers (Optimized Approach)
Alternatively, we can utilize two pointer variables to check a string for a palindrome. It is such that the first pointer starts from the initial(0th) index of the string and moves in the forward direction(left to right). The other one starts from the last/end of the string and advances in the backward direction(right to left). Also, we will compare the characters of both pointers at each index. If they are the same, the pointers will advance to the next indexes. If they aren’t the same, a boolean “false” will be retrieved, as shown below:
import java.util.Scanner;
public class PalindromeExample {
public static boolean checkPalindrome(String inputStr) {
int pointer1 = 0;
int pointer2 = inputStr.length() - 1;
while (pointer1 < pointer2) {
if (inputStr.charAt(pointer1) != inputStr.charAt(pointer2))
return false;
pointer1++;
pointer2--;
}
return true;
}
//the main() method
public static void main(String[] args) {
System.out.println("Enter a String to Check for Palindrome");
Scanner scanInput = new Scanner(System.in);
String inputStr = scanInput.next();
inputStr = inputStr.toLowerCase();
if (checkPalindrome(inputStr))
{
System.out.println("Yes! the Given String is Palindrome");
}
else
{
System.out.println("No! the Given String is not a Palindrome");
}
scanInput.close();
}
}
In the main() method,
- First, we prompt a message that asks the user to enter a string using the Scanner class.
- Up next, we convert the provided string to lowercase.
- Finally, we invoke the checkPalindrome() method with the input string and print the result on the console.
Method 4: Check Palindrome String Using Recursion
Recursion is a process in which a method calls itself recursively until it meets the base/stopping condition. You can use this approach to check/match the palindrome strings:
import java.util.Scanner;
public class PalindromeExample { public static boolean isPalindrome(String inputStr) {
return checkPalindrome(0, inputStr.length() - 1, inputStr);
}
public static boolean checkPalindrome(int pointer1, int pointer2, String inputStr) {
if (pointer1 >= pointer2) {
return true;
}
if (inputStr.charAt(pointer1) != inputStr.charAt(pointer2)) {
return false;
}
return checkPalindrome(pointer1 + 1, pointer2 - 1, inputStr);
}
//the main() method
public static void main(String[] args) {
System.out.println("Input a String/Word to Check for Palindrome");
Scanner scanInput = new Scanner(System.in);
String inputStr = scanInput.next();
inputStr = inputStr.toLowerCase();
boolean result = isPalindrome(inputStr);
System.out.println("The Given String is Palindrome? ==> " + result);
scanInput.close();
}
}
In the above code,
- The “isPalindrome()” is a user-defined method that accepts an input string as its parameter. It invokes the recursive method “checkPalindrome()” with three arguments: the initial index “0”, the total length of the input string, and the input string.
- The checkPalindrome() is a recursive method that takes three parameters: pointer1, pointer2, and inputStr. It checks if the given string “inputStr” from pointer1 to pointer2 is a palindrome or not.
- If pointer1 becomes greater than or equal to pointer2, this means the entire string has been traversed/checked, so it retrieves true.
- We use the charAt() method with the pointer1 and pointer2 to check if the characters at positions pointer1 and pointer2 are equal. If they aren’t equal, retrieve false, otherwise, it calls itself recursively with updated pointers.
- In the main() method, first, the input/user-entered string is converted into lowercase. This lowercase string is then passed to the “isPalindrome()” method to check if it is palindrome or not:
How to Check Palindrome Numbers in Java
A number can also be a palindrome, such as “121”, “51215”, “172271”, etc. Similar to palindrome strings, you can use different Java methods/approaches to check palindrome numbers. For instance, in the following code, we reverse the given number using the while loop and compare the reversed number with the actual number to check if it is palindrome or not:
import java.util.Scanner;
public class PalindromeExample {
public static void checkPalindrome(int inputNum) {
int tempNum, mod, revNum = 0;
tempNum = inputNum; //reversing the given number
while (inputNum > 0) {
mod = inputNum % 10;
revNum = (revNum * 10) + mod;
inputNum = inputNum / 10;
}
if (tempNum == revNum)
System.out.println("The Given Number is palindrome");
else
System.out.println("The Given Number is Not a palindrome");
}
//the main() method
public static void main(String[] args) {
System.out.println("Enter a Number to Check for Palindrome");
Scanner scanInput = new Scanner(System.in);
int inputNum = scanInput.nextInt();
checkPalindrome(inputNum);
scanInput.close();
}
}
In the above code,
- First, we create a “checkPalindrome()” method that accepts a number that needs to be checked for palindrome.
- Within this method, we create and initialize a variable “temp” with a user-entered number. A “mod” variable to store the modulus/remainder of the given number. And a variable “revNum” to store the reversed number/integer.
- We execute a while loop to iterate every digit of the given number. Within the loop’s body, we utilize the modulus operator to reverse the provided number.
- Finally, we use the if-else statement with the equality “==” operator to check if the provided number is palindrome or not.
- In the main() method, we get an integer from the user and pass it to the “checkPalindrome()” method:
That’s all about checking palindrome strings in Java.
Final Thoughts
To check palindrome strings in Java, use the “StringBuffer” class, “for loop”, “recursion”, or “two pointer variables” method. The “StringBuffer” is the most convenient among all these approaches. Using this approach, first, you reverse the given string using its built-in “reverse()” method. After this, you can execute the equals() method to compare the actual and reversed string. If both of them are equal; this means the given string is a palindrome else the provided string is not a palindrome. Alternatively, you can use any of the mentioned approaches to check the palindrome strings in Java. This guide has extensively illustrated several methods to check palindrome strings in Java.