Java Program to Check Palindrome
To understand this example, you should have the knowledge of the following Java programming topics:
A string is called a palindrome string if the reverse of that string is the same as the original string. For example, radar , level , etc.
Similarly, a number that is equal to the reverse of that same number is called a palindrome number. For example, 3553, 12321, etc.
To check a Palindrome in Java, we first reverse the string or number and compare the reversed string or number with the original value.
Example 1: Java Program to Check Palindrome String
class Main < public static void main(String[] args) < String str = "Radar", reverseStr = ""; int strLength = str.length(); for (int i = (strLength - 1); i >=0; --i) < reverseStr = reverseStr + str.charAt(i); >if (str.toLowerCase().equals(reverseStr.toLowerCase())) < System.out.println(str + " is a Palindrome String."); >else < System.out.println(str + " is not a Palindrome String."); >> >
Radar is a Palindrome String.
In the above example, we have a string «Radar» stored in str . Here, we have used the
1. for loop to reverse the string
- The loop runs from the end to the beginning of the string.
- The charAt() method accesses each character of the string.
- Each character of the string is accessed in reverse order and stored in reverseStr .
2. if statement to compare str and reverseStr
- The toLowerCase() method converts both str and reverseStr to lowercase. This is because Java is case sensitive and ‘r’ and ‘R’ are two different values.
- The equals() method checks if two strings are equal.
Example 2: Java Program to Check Palindrome Number
class Main < public static void main(String[] args) < int num = 3553, reversedNum = 0, remainder; // store the number to originalNum int originalNum = num; // get the reverse of originalNum // store it in variable while (num != 0) < remainder = num % 10; reversedNum = reversedNum * 10 + remainder; num /= 10; >// check if reversedNum and originalNum are equal if (originalNum == reversedNum) < System.out.println(originalNum + " is Palindrome."); >else < System.out.println(originalNum + " is not Palindrome."); >> >
In the above example, we have a number 3553 stored in num and originalNum variables. Here, we have used the
- while loop to reverse num and store the reversed number in reversedNum
- if. else to check if reversedNum is same as the originalNum
Java program to check palindrome string
Learn to check if a given string is palindrome string with simple java programs using stack, queue or simple loops. In simplest words, a string is palindrome if it is equal to it’s reverse string.
A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, generally if used comma, separators or other word dividers are ignored.
1.1. First approach
To check palindrome, we can pick the characters (one by one) from start and end of string and start comparing to each other.
- Pick first character and last character of string and compare. If both matches – continue. Else string is not palindrome.
- Pick second character from start and last, compare both. If both matches – continue. Else string is not palindrome.
- Continue above comparisons till both characters to compare are same or consecutive to each other.
1.2. Second approach
Rather than comparing chars from start and end, we can also find the reverse string of the given string and compare both strings. If both strings are same, they are palindrome.
- Get character array from given string
- Build a string by iterating the array from end to beginning index
- Optionally – remove comma, separators or other word dividers from both strings
- Compare both strings
In this tutorial, we will see the examples of both approaches.
2. Check palindrome using reverse comparison
This method uses the first approach given above.
import java.util.Scanner; public class Main < public static void main(String[] args) < System.out.print("Enter any string : "); Scanner in = new Scanner(System.in); //Original string String origString = in.nextLine(); int length = origString.length(); boolean isPalindrome = true; for(int beginIndex = 0; beginIndex < length; beginIndex++) < if(origString.charAt(beginIndex) != origString.charAt(length-1-beginIndex)) < System.out.println("String is not a palindrome."); isPalindrome = false; break; >> if(isPalindrome) < System.out.println("String is a palindrome."); >> >
Enter any string : howtodoinjava String is not a palindrome. Enter any string : madam String is a palindrome.
3. Check palindrome using StringBuilder.reverse()
StringBuilder.reverse() method is shortest way to reverse a string using library functions.
import java.util.Scanner; public class Main < public static void main(String[] args) < System.out.print("Enter any string : "); Scanner in = new Scanner(System.in); //Original string String origString = in.nextLine(); //Reverse string String reverseString = new StringBuilder(origString).reverse().toString(); // Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
Enter any string : howtodoinjava String is not a palindrome. Enter any string : madam String is a palindrome.
4. Check palindrome string using java.util.Stack
Using stack’s push() and pop() methods, we can build a reverse string for a given string. Then we compare both strings.
import java.util.Scanner; import java.util.Stack; public class Main < public static void main(String[] args) < System.out.print("Enter any string : "); Scanner in = new Scanner(System.in); String origString = in.nextLine(); Stackstack = new Stack<>(); //Push all chars in stack for (int i = 0; i < origString.length(); i++) < stack.push(origString.charAt(i)); >String reverseString = ""; //Pop all chars from stack one by one and build reverse string while (!stack.isEmpty()) < reverseString = reverseString + stack.pop(); >//Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
Enter any string : howtodoinjava String is not a palindrome. Enter any string : racecar String is a palindrome.
5. Check palindrome string using java.util.Queue
Using Queue’s add() and remove() methods, we can build a reverse string for a given string. Then we compare both strings.
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main < public static void main(String[] args) < System.out.print("Enter any string : "); Scanner in = new Scanner(System.in); String origString = in.nextLine(); Queuequeue = new LinkedList<>(); for (int i = origString.length()-1; i >=0; i--) < queue.add(origString.charAt(i)); >String reverseString = ""; //Pop all chars from stack one by one and build reverse string while (!queue.isEmpty()) < reverseString = reverseString + queue.remove(); >//Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
Enter any string : howtodoinjava String is not a palindrome. Enter any string : racecar String is a palindrome.
6. Check palindrome string using loops
This is simplest approach which simply iterated the char array backwards and creates the string by appending chars to produce reverse string.
import java.util.Scanner; public class Main < public static void main(String[] args) < System.out.print("Enter any string : "); Scanner in = new Scanner(System.in); String origString = in.nextLine(); String reverseString = ""; char[] characters = origString.toCharArray(); for( int i = characters.length - 1 ; i >= 0 ; i-- ) < reverseString = reverseString + characters[i]; >//Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
Enter any string : water String is not a palindrome. Enter any string : madam String is a palindrome.
Drop me your questions related to check whether the given string is a palindrome or not in java .
How to check Palindrome String in java?
In this article, we will find string palindromes in Java, it works the same as in integer. The meaning of the palindrome string is that if we start reading it from right to left or left to right it is the same in both cases.
Algorithm
Approach 1
For checking string palindromes in java, we can choose the characters one by one from the start and end of the string and compare each other. => Choose the first and the last character of the string and compare, if both the characters match then continue, else the string is not a palindrome.
=> Choose the second character from the first and last of the string and compare, if both match — continue, else return string is not a palindrome.
=> Continue the above comparisons till both the characters to compare are the same or adjacent to each other.
Approach 2
Instead of comparing the characters from start to end, we can find the reverse string of the given string and compare both the strings, if they are the same that means the string is a palindrome. => From given string, get character array
=> Create a string by iterating the array from the end to the start index.
=> Remove separator, comma, or other dividers from both the strings (Optional)
=> Finally, compare both the strings Example 1. String Palindrome in java using Loop
import java.util.Scanner; public class Main < public static void main(String[] args) < System.out.print("Enter any string : "); Scanner in = new Scanner(System.in); String origString = in.nextLine(); String reverseString = ""; char[] characters = origString.toCharArray(); for( int i = characters.length - 1 ; i >= 0 ; i-- ) < reverseString = reverseString + characters[i]; >//Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
Output:
Enter any String: Weather
String is not a palindrome. Enter any String: Naman
String is a palindrome. Example
class Main < public static void main(String[] args) < String str = "Radar", reverseStr = ""; int strLength = str.length(); for (int i = (strLength - 1); i >=0; --i) < reverseStr = reverseStr + str.charAt(i); >if (str.toLowerCase().equals(reverseStr.toLowerCase())) < System.out.println(str + " is a Palindrome String."); >else < System.out.println(str + " is not a Palindrome String."); >> >
import java.util.Scanner; import java.util.Stack; public class Main < public static void main(String[] args) < System.out.print("Enter the string : "); Scanner in = new Scanner(System.in); String origString = in.nextLine(); Stackstack = new Stack<>(); //Push all chars in stack for (int i = 0; i < origString.length(); i++) < stack.push(origString.charAt(i)); >String reverseString = ""; //Pop all chars from stack one by one and build reverse string while (!stack.isEmpty()) < reverseString = reverseString + stack.pop(); >//Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main < public static void main(String[] args) < System.out.print("Enter the string : "); Scanner in = new Scanner(System.in); String origString = in.nextLine(); Queuequeue = new LinkedList<>(); for (int i = origString.length()-1; i >=0; i--) < queue.add(origString.charAt(i)); >String reverseString = ""; //Pop all chars from stack one by one and build reverse string while (!queue.isEmpty()) < reverseString = reverseString + queue.remove(); >//Check palindrome string if (origString.equals(reverseString)) < System.out.println("String is a palindrome."); >else < System.out.println("String is not a palindrome."); >> >
Output:
Enter the string: racecar
String is a palindrome. Enter the string: java
String is not a palindrome.
Conclusion
In this blog, we took in the string palindrome in the Java issue. We had examined two methodologies for the string palindrome in Java issue with the clarification of existence intricacy. We truly want to believe that you are delighted in perusing this blog. Evaluate additional string issues in Java, similar to switch a string, check in the event that a number is a palindrome, check in the event that two given strings are isomorphic to one another, base characters to be added at front to make string palindrome, and so forth. In java there are multiple concepts that can be learned at initial and mid level to get expertise in java. Some of the concepts like final keywords in java, javascript basics, oops concepts etc.