String palindrome in java using array

Let’s learn string palindrome in java using array.

String palindrome in java using array

To do that first convert user entered string into character array using toCharArray() method.

In the next step make a copy of user entered string into another character array using copyOf() method of Arrays class.

Now reverse array. Compare user entered array with reversed array. If both array are same then string is palindrome else string is not palindrome.

Here’s the program to check a string for palindrome using array.

import java.util.Arrays;
import java.util.Scanner;
public class StringPalindromeUsingArray 
{
   public static void main(String[] args) 
   {
      System.out.println("Please enter string to check whether string is palindrome: ");
      Scanner sc = new Scanner(System.in);
      String strInput = sc.nextLine();
      char[] chArray = strInput.toCharArray();
      int size = chArray.length;
      char[] chGiven = Arrays.copyOf(chArray, chArray.length);
      for(int a = 0; a < size / 2; a++) 
      {
         char temp = chArray[a];
         chArray[a] = chArray[size - a - 1];
         chArray[size - a - 1] = temp;
      }
      System.out.println("Given array: " + Arrays.toString(chGiven));
      System.out.println("String palindrome using array: " + Arrays.toString(chArray));
      if(Arrays.equals(chArray, chGiven)) 
      {
         System.out.println("string is palindrome.");
      }
      else 
      {
         System.out.println("string is not a palindrome.");
      }
      sc.close();
   }
}

Output:

Please enter string to check whether string is palindrome: madam
Given array: [m, a, d, a, m]
String palindrome using array: [m, a, d, a, m]
string is palindrome.

Please enter string to check whether string is palindrome: hello
Given array: [h, e, l, l, o]
String palindrome using array: [o, l, l, e, h]
string is not a palindrome.


Also read – interface in java