Check whether String is Palindrome or Not in Java.

Java Program to Check whether String is Palindrome or Not.


String is called Palindrome, if it is read same from front as well as from back.
In this post, we will see Algorithm to check whether string is palindrome or not.


Java Program to check whether String is Palindrome or not.


It is very easy to check whether String is Palindrome or not.

Approach 1:

Reverse the original string and compare Reversed String with original string.
If reversed string and original string is same then String is Palindrome else not.

class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome("ABCBA"));
 }  

 public static boolean isPalindrome(String originalString){
  if(originalString == null){
   return true;
  }
  
  String reversedString = "";
  for (int i = originalString.length()-1; i >= 0; i--) {
   reversedString += originalString.charAt(i); 
  }
  
  return originalString.equals(reversedString);
 }
} 


Approach 2: In this approach, we will check whether String is Palindrome or not by comparing the characters of string from front and back together.

STEP: 1
Take 2 variable, pointer1 and pointer2. 
pointer1 initialise to index 0 and pointer2 initialise to originalString.length()-1.

STEP 2:
Compare characters at pointer1 and pointer2, if they are not same, then they are not Palindrome and stop.
If they are same then increment pointer1, decrement pointer2.

Repeat STEP 2 til pointer1 < pointer2.


class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome("ABCBA"));
 }  

 public static boolean isPalindrome(String originalString){
  int pointer1 = originalString.length()-1;
  int pointer2=0;
  while(pointer1 > pointer2) {
   if(originalString.charAt(pointer1) != originalString.charAt(pointer2)) {
    return false;
   }
   pointer1--;
   pointer2++;
  }
  return true;
 }
} 


You may also like to see




Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment