Palindrome String Example
Input
‘S’ = ‘abba’
Output
YES
Explanation:
We can see that the string is the same from left to right and right to left.
abba = abba,
So it is a string palindrome in java.
Now, Let's learn to write a string palindrome program in java.
Methods to Check String Palindrome in Java
In this section, we will discuss how we can actually find if the given string is palindrome or not. There are mainly two methods to check string palindrome in Java; here are the following methods:
1. Naive Approach to Check if a String is Palindrome in Java
This will be our first and basic approach to checking the palindrome string. We know if the given string (on which we have to check for palindrome) and its reverse are equal, then we can say the string is a palindrome; otherwise, not. So we will be doing this process in this approach; here are some of the steps to understand this approach:
Step 1: First, we have to initialize the given string and its reversed string with “” because we will store the reverse of the given string to this.
Step 2: We will iterate through the given string from end to start so that we can have the reverse of this string, and while iterating, we will store each character in the extra created string.
Step 3: Now we have the given string and its reversed string, we can now compare both of them. While comparing, we also have to convert them to lowercase, and If they are the same, then the given string is palindrome or else not.
Here's the implementation of Java code for this naive approach:
Java
class Main {
public static void main(String[] args) {
// Here are two strings 's' is the string for which we have to check for palindrome.
// 'rev_s' will be the reverse of 's', initialized with "" right now.
String s = "Ninja", rev_s = "";
// 'n' is the length of s.
int n = s.length();
// Looping through the 's' from end to start and storing each character to 'rev_s', so that 'rev_s' will store the reverse of 's'.
for(int i = n - 1; i >= 0; i--)
rev_s += s.charAt(i);
// Now for comparing, we have to compare both the strings to lowercase and then compare them, If they are equal then 's' is palindrome Else not.
if(s.toLowerCase().equals(rev_s.toLowerCase()))
System.out.println(s + " is a Palindrome String.");
else
System.out.println(s + " is not a Palindrome String.");
}
}

You can also try this code with Online Java Compiler
Run Code
The output of the above implementation:
Ninja is not a Palindrome String.
2. Check Palindrome Using Recursive Approach in Java
This will be our second recursive approach, where we will not use any extra memory or space. As we used a reversed string of the given string for comparison, but here we will not use any extra space. Instead, we will use recursion to solve our problem. The intuition of the approach is to compare the first and the last index character at a time, If we continue this for every character; the problem will be solved. Here are the steps that we will be going to use in this approach:
Step 1: First, we will initialize the given string with any value. let's just say “Ninjas”.
Step 2: Now, we will call the recursive function that returns the boolean value (True or False). If the function returns true, the given string is a palindrome; otherwise, not.
Step 3: Now, what we have to do is iterate the string with start + 1 and end - 1 as we are comparing the start and the end index character.
Step 4: If anytime start gets equal to the end (base condition), means the given string is palindrome, and there are no more characters for comparison.
Step 5: If the character at the start and end are equal, we can continue the process till the base condition meets. Else if the characters are not equal, we don't have to continue the process, and we can return false.
Here's the implementation of Java code for this recursive approach:
Java
public class Main {
public static boolean isPalindrome(String s, int start, int end) {
// First we will check if the 'start' is equal to 'end';
// Means there are no more characters to check and its a palindrome strins. So return true.
if (start == end)
return true;
// Checking if the characters are equal, so we will move to next step.
// To move to a next step, we have increment 'start' and decrement 'end'.
if (s.charAt(start) == s.charAt(end))
return isPalindrome(s, start + 1, end - 1);
// If the characters are not equal, No need to move just return false.
return false;
}
public static void main(String[] args) {
// Initialize givens string 's' with any value.
String s = "Ninjas";
// 'n' is the length of 's' string.
int n = s.length();
// If the recursive function 'isPalindrome' return true, means the string is palindrome. else not.
if(isPalindrome(s.toLowerCase(), 0, n - 1))
System.out.println(s + " is a palindrome.");
else
System.out.println(s + " is not a palindrome.");
}
}

You can also try this code with Online Java Compiler
Run Code
The output of the above implementation:
Ninjas is not a palindrome.
3. Palindrome String Check in Java Using Two Pointer Method
This is the 3rd approach where we will see how efficiently we can find whether the string is palindrome or not using the two-pointer approach.
Step 1: The strategy will be to first transform the string to lowercase.
Step 2: Take two pointers, 'i' pointing to the beginning of the string and 'j' pointing to the end.
Step 3: Continue to increment i and decrease j while i < j and check whether the characters at these addresses are the same or not at each step. If not, the string is not a palindrome; otherwise, it is.
Here's the implementation of Java code for this two pointer approach approach:
Java
public class Ninja {
// Return true if string is palindrome
static boolean isPalindrome(String s)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void main(String[] args)
{
String s = "121nitin121";
// Convert the string to lowercase
s = s.toLowerCase();
if (isPalindrome(s))
// It is a palindrome
System.out.print(s+" "+"is palindrome");
else
// Not a palindrome
System.out.print(s+" "+"is not palindrome");
}
}

You can also try this code with Online Java Compiler
Run Code
The output of the above implementation:
121nitin121 is palindrome
4. Palindrome String Check in Java Using Iteration
To check if a string is a palindrome using iteration, you can compare characters from the beginning and end of the string, moving towards the center. If all corresponding characters match, the string is a palindrome.
Example:
Java
public class PalindromeIteration {
public static void main(String[] args) {
String str = "radar"; // Example string
boolean isPalindrome = isPalindrome(str);
System.out.println("Is the string \"" + str + "\" a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Is the string "radar" a palindrome? true
5. Java Program to Check Palindrome String Using Recursion
A recursive approach involves checking if the first and last characters of the string are the same, and then recursively checking the substring that excludes these characters. If the base case of the recursion is reached (an empty or one-character string), the string is a palindrome.
Example:
Java
public class PalindromeRecursion {
public static void main(String[] args) {
String str = "level"; // Example string
boolean isPalindrome = isPalindrome(str);
System.out.println("Is the string \"" + str + "\" a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(String str) {
if (str.length() <= 1) {
return true;
}
if (str.charAt(0) != str.charAt(str.length() - 1)) {
return false;
}
return isPalindrome(str.substring(1, str.length() - 1));
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Is the string "level" a palindrome? true
6. Java Program to Check Palindrome Using Stack
A stack can be used to check if a string is a palindrome by pushing all characters of the string onto the stack, then popping them off and comparing them with the original string. Since a stack is a Last-In-First-Out (LIFO) data structure, the characters will come off in reverse order.
Explanation:
- Push all characters of the string onto the stack.
- Pop each character from the stack and build a reversed string.
- Compare the original string with the reversed string; if they are the same, the string is a palindrome.
Example:
Java
import java.util.Stack;
public class PalindromeStack {
public static void main(String[] args) {
String str = "madam"; // Example string
boolean isPalindrome = isPalindrome(str);
System.out.println("Is the string \"" + str + "\" a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(String str) {
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
stack.push(c);
}
StringBuilder reversedStr = new StringBuilder();
while (!stack.isEmpty()) {
reversedStr.append(stack.pop());
}
return str.equals(reversedStr.toString());
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Is the string "madam" a palindrome? true
7. Palindrome Check in Java Using StringBuilder Approach
The StringBuilder approach in Java is a simple and efficient way to check if a string is a palindrome. This method takes advantage of the reverse() method provided by the StringBuilder class.
How It Works:
- Take the original string.
- Create a StringBuilder object with that string.
- Reverse the StringBuilder.
- Compare the reversed string with the original.
Example:
Java
public class PalindromeCheck {
public static void main(String[] args) {
String input = "madam";
// Create StringBuilder and reverse it
StringBuilder sb = new StringBuilder(input);
String reversed = sb.reverse().toString();
// Compare original and reversed strings
if (input.equals(reversed)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
madam is a palindrome.
Complexities of String Palindrome in Java
Time Complexity
O(N), where ‘N’ is the length of the string
Reason: As we are looping over the entire string only once, it will cost us O(N) time to solve the problem ‘string palindrome in java’.
Space Complexity
O(1).
Reason: We are not using any extra variable space thus the space complexity would be O(1) for the problem ‘string palindrome in java’.
Palindrome BigInteger Number
A BigInteger is used in Java to handle very large integer values that exceed the limits of primitive data types like int and long. To check if a BigInteger is a palindrome, you can convert it to a string and then apply the same logic as checking if a string is a palindrome.
Explanation:
- Convert the BigInteger to a String: Since a palindrome is a sequence that reads the same backward as forward, converting the number to a string allows us to easily check the sequence.
- Check for Palindrome: Compare characters from the beginning and end of the string, moving towards the center, to determine if the number is a palindrome.
Example:
Java
import java.math.BigInteger;
public class PalindromeBigInteger {
public static void main(String[] args) {
BigInteger bigNumber = new BigInteger("12345654321"); // Example BigInteger
boolean isPalindrome = isPalindrome(bigNumber);
System.out.println("Is the BigInteger " + bigNumber + " a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(BigInteger bigNumber) {
String str = bigNumber.toString();
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Is the BigInteger 12345654321 a palindrome? true
Frequently Asked Questions
What is a palindrome number in Java?
A palindrome number in Java is a number that reads the same forwards and backwards, such as 121 or 1331, making it identical when reversed.
Is palindrome a possible program in Java?
Yes, a palindrome program is possible in Java using string manipulation or mathematical operations to check whether a number or string reads the same forwards and backwards.
How do you find the palindrome between two numbers in Java?
To find palindromes between two numbers in Java, iterate through the range, convert each number to a string, and check if it reads the same forward and backward. Print or store numbers that meet this condition.
How do you make a string palindrome?
A palindrome string is a string that is the same when read from left to right or right to left. To make a string palindrome we have to make its left half equal to its right half. This can be done by concatenating the reverse of the original string to the original string. In this way, we can make a string palindrome.
What is palindrome string logic?
The logic of the problem palindrome string is that we need to find if a string is the same when read left to right and right to left. To check this we can use two pointers to iterate simultaneously from left to right and right to left and check it the corresponding characters are the same or not. If they are the same for all the indexes then the answer will be yes, else no.
Is 12321 a palindrome?
Yes, 12321 is a palindrome because it reads the same forwards and backwards, making it identical in both directions.
Conclusion
We saw how we discussed the Java Program to Check if a String is Palindrome. and wrote a string palindrome program in java. Other problems involving strings and similar to the problem ‘string palindrome in java’ are Lexicographically largest String after removal of K characters, Count of Increasing Substrings in given String, String Interview Questions In Java, etc.
Recommended Readings: