Java program to check given string is Palindrome or not | use getChars() & StringBuffer

The following code accepts a string, and checks whether the given string is Palindrome or not using two methods .

Steps to check Palindrome or not.
1. Get the input String
2. Find reverse of the given string
3. Match the original string with reverse string, If both are equal, then given string is Palindrome, Otherwise Not.

Using Method 1:
As String class doesn’t have any reverse method, we have to convert the sting to array of characters, then using loop,get the reverse of the string. Now follow the above step 3.

Using Method 2:
In this method, it is very easy to check the given string is Palindrome or not. First convert the String to StringBuffer. As StringBuffer class has reverse method, we can find the reverse of the string easily . Now follow the step 3.

package com.javaonline;

import javax.swing.JOptionPane;

public class Palindrome {
    public static void main(String[] args) {

  String inputString =  JOptionPane.showInputDialog("Enter any column number: ");  // Getting Input

	System.out.println("\n");
	System.out.println("Palindrome check using Method1");
	 Method1(inputString); 
	System.out.println("Palindrome check using Method2");
	 Method2(inputString);
    
    }

//Check Palindrome or not  using getChars() & Loop
private static void Method1(String inputStr)

{

     int len = inputStr.length();
     char[] charArray = new char[len];
     String rev="";

 // Converting  String to  array of chars using getChars();
     inputStr.getChars( 0,  len, charArray,  0) ;
//Converting Reverse String 
     for (char c:charArray)  rev=c+rev;

   if (inputStr.equalsIgnoreCase(rev) ) 
	   System.out.println("Given String " + inputStr + " is Palindrome\n"); 
   else 
	   System.out.println("Given String " + inputStr + " is not Palindrome\n");

}


//Check Palindrome or not  using StringBuffer class

private static void Method2(String inputStr)

{
  StringBuffer strBuffer = new StringBuffer(inputStr);
   if (inputStr.equalsIgnoreCase(strBuffer.reverse().toString()) )  
	   System.out.println("Given String " + inputStr + " is Palindrome\n"); 
   else 
	   System.out.println("Given String " + inputStr + " is not Palindrome\n");

}

}

Run the program

Input: Liril

palindrome

 

Input: Java

 

palindrome1

You may also like