Java program to check string as palindrome


A string is Palindrome if position of each character remain same in case even string is reversed.For example 'MADAM' is a palidrome string as position of each character remain same even if string 'MADAM' is reversed.Now in order to identify a string as palindrome or not we can use library method approach and also without library method approach.

But if we want to check if "Madam" is palindrome or not , it will show us that it is not a palindrome because of the upper case of first letter.

Example - Without library method.

 Live Demo

public class Palindrome {
   public static void main(String[] args) {
      String str = "SATYA";
      StringBuffer newStr =new StringBuffer();
      for(int i = str.length()-1; i >= 0 ; i--) {
         newStr = newStr.append(str.charAt(i));
      }
      if(str.equalsIgnoreCase(newStr.toString())) {
         System.out.println("String is palindrome");
      } else {
         System.out.println("String is not palindrome");
      }
   }
}

Output

String is not palindrome

Example - With library method.

 Live Demo

public class Palindrome {
   public static void main (String[] args) throws java.lang.Exception {
      String str = "NITIN";
      String reverse = new StringBuffer(str).reverse().toString();
      if (str.equals(reverse))
      System.out.println("String is palindrome");
      else
      System.out.println("String is not palindrome");
   }
}

Output

String is palindrome

Updated on: 23-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements