Java Program to check a given string is palindrome or not.
Objective
Write a Java program to check if a string is a palindrome.
Algorithm / Approach
- Accept a string from the user.
- Pass it to a
reverse()method (identical to the previous program) to get its reversed version. - Use the
equals()method to compare the original string with the reversed string. - If they match, print "Palindrome". Otherwise, print "Not Palindrome".
Test.java
import java.util.Scanner;
class Test {
public String reverse(String x) {
String rev = "";
for(int i=x.length()-1; i>=0;i--) {
rev = rev + x.charAt(i);
}
return rev;
}
public static void main(String[] a)
{
Test t = new Test();
Scanner s=new Scanner(System.in);
System.out.print("Enter String: ");
String s1 = s.nextLine();
String s2 = t.reverse(s1);
if(s1.equals(s2)) {
System.out.print("Palindrome");
}
else {
System.out.print("Not Palindrome");
}
}
}
Expected Output
Enter String: MADAM Palindrome
Explanation of the Program
- A palindrome is a word, phrase, or sequence that reads the same backward as forward (e.g., "MADAM", "RACECAR").
- By utilizing the string reversing logic we already built, the logic for checking a palindrome becomes extremely simple: just check if
original.equals(reversed). - This program is case-sensitive, so "Madam" would not be considered a palindrome unless converted to a uniform case first.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)