Write a Java program that accepts a string and checks whether a given string is a palindrome or not.
What is String Palindrome Program in Java?
A palindrome is a word, phrase, or sentence that reads the same backward or forward. A string is said to be a palindromic string when we traverse it from start to end or end to start then we get the same result.
Examples: ada, malayalam, racecar, mom, etc.
Let us take a few more examples to understand the problem.
Example 1:
Input: String = “RACECAR”
Output: racecar is a Palindrome
Explanation: The reverse of the given string is equal to the (RACECAR) is equal to the given string. Therefore, the given string is a palindromic string.
Example 2:
Input: String = “SANFOUNDRY”
Output: SANFOUNDRY is not a Palindrome
Explanation: The reverse of the given string is equal to the (YRDNUOFNAS) which is not equal to the given string. Therefore, the given string is not a palindromic string.
1. Take a string as input.
2. Reverse the string.
3. If they are equal, print the string is a Palindrome else print, the string is not a palindrome.
Here is the source code of the Java Program to Check whether a String is a Palindrome. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Palindrome { public static void main(String args[]) { String a, b = ""; Scanner s = new Scanner(System.in); System.out.print("Enter a string:"); a = s.nextLine(); int n = a.length(); for(int i = n - 1; i >= 0; i--) { b = b + a.charAt(i); } if(a.equalsIgnoreCase(b)) { System.out.println(a+ " is a palindrome."); } else { System.out.println(a+ " is not a palindrome."); } } }
1. Take a string as input and store it in the array.
2. Use for loops and if-else conditions along with equalsIgnoreCase() method to conclude whether the entered string is palindrome or not.
Testcase 1: In this case, we enter the string “sanfoundry” as input to check whether it is a palindrome string or not.
Enter a string: sanfoundry sanfoundry is not a palindrome
Testcase 2: In this case, we enter the string “racecar” as input to check whether it is a palindrome string or not.
Enter a string: racecar racecar is a palindrome
To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.
- Apply for Java Internship
- Apply for Computer Science Internship
- Check Programming Books
- Practice Programming MCQs
- Practice Information Technology MCQs