Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to check a given string is palindrome or not.

Java Code Example — String Programs

ADVERTISEMENT

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

  1. Accept a string from the user.
  2. Pass it to a reverse() method (identical to the previous program) to get its reversed version.
  3. Use the equals() method to compare the original string with the reversed string.
  4. 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)
ADVERTISEMENT