Palindrome program in Java

Here are a few ways for checking for Palindrome in java.
 
 

Example 1: Palindrome using StringBuffer

 
This program demonstates testing for a Palindrome word using StringBuffer.
 
We accept a work from keyboard(System.in) and assign it to inputString.
 
Then we created a StringBuffer with this and reverse it.
 
If the inputString and StringBuffer contents match, it’s a Palindrome.
 

package com.javatutorial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExamplePalindromeUsingStringBuffer {

  public static void main(String[] args) throws IOException {
    
    System.out.println("Enter a string");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    String inputString = br.readLine();
    
    StringBuffer sb = new StringBuffer(inputString);
    
    sb.reverse();
    
    String newStrnig = sb.toString();
    
    if(newStrnig.equalsIgnoreCase(inputString))
      System.out.println(inputString + " is a Palindrome");
    else
      System.out.println(inputString + " is NOT a Palindrome");
  }

}


 
 
Output :
 
Enter a string
racecar
racecar is a Palindrome
 
 

Example 2: Palindrome without String functions

 
This program demonstrates testing for a Palindrome using char[].
 
This method loops through each character in reverse order and checks if it matches the character at corresponding position in original array.
 

package com.javatutorial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExamplePalindrome {

  public static void main(String[] args) throws IOException {

    System.out.println("Enter a string");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
    String input = br.readLine();
    
    System.out.println(IsPalindrome(input.toCharArray()));
  }
  
  public static String IsPalindrome(char[] word)
    {
        int min = 0;
        int max = word.length - 1;
        
        while(max > min){
          if(word[max] != word[min]){
            return "not a palindrome";
          }
          min ++;
          max --;
        }
     return "palindrome";
    }

}

 
 
Output:
 
Enter a string
anna
palindrome

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags