Thursday, March 1, 2018

Java Program to check whether given word is Palindrome or not


This post will explain us, how to implement palindrome logic with different ways, using java.

public class WordPalindrome {
  public static void main(String[] args) {
   String word="LIRIL";
   boolean isPalin = isPalindromeOne(word);
   if(isPalin){
    System.out.println("Given word ["+word+"] is palindrome");
   }else{
    System.out.println("Given word ["+word+"] is not palindrome");
   }
   word = "Hello";
   isPalin = isPalindromeOne(word);
   if(isPalin){
    System.out.println("Given word ["+word+"] is palindrome");
   }else{
    System.out.println("Given word ["+word+"] is not palindrome");
   }
   
  }


  public static boolean isPalindromeOne(String word){
   boolean isPalindrome = false;
   //first way of checking
   char[] array = word.toCharArray();
   char[] newArray = new char[array.length];
   for (int i = 0; i < array.length; i++) {
  char c = array[array.length-i-1];
  newArray[i] =(char)c;
 }
   if(word.equalsIgnoreCase(String.valueOf(newArray))){
    isPalindrome = true;
   }
   //second way of checking
   String reverse ="";
   for (int i = 0; i < word.length(); i++) {
  char c= word.charAt(i);
  reverse = c+reverse;
 }
   if(reverse.equalsIgnoreCase(word)){
    isPalindrome = true; 
   }
   
   
 
   return isPalindrome;
  }
  
  
  
}


AddToAny

Contact Form

Name

Email *

Message *