How to check a String for palindrome using arrays in java?

Java 8Object Oriented ProgrammingProgramming

To verify whether the given string is a palindrome (using arrays)

  • Convert the given string into a character array using the toCharArray() method.
  • Make a copy of this array.
  • Reverse the array.
  • Compare the original array and the reversed array.
  • in case of match given string is a palindrome.

Example

import java.util.Arrays;
import java.util.Scanner;

public class Palindrome {
   public static void main(String args[]) {
      System.out.println("Enter a string ");
      Scanner sc = new Scanner(System.in);
      String s = sc.nextLine();
      char[] myArray = s.toCharArray();
      int size = myArray.length;
      char [] original = Arrays.copyOf(myArray,myArray.length);

      for (int i = 0; i < size / 2; i++) {
         char temp = myArray[i];
         myArray[i] = myArray[size-i-1];
         myArray[size-i-1] = temp;
      }
      System.out.println("Original Array"+Arrays.toString(original));
      System.out.println("Reverse Array"+Arrays.toString(myArray));

      if(Arrays.equals(myArray, original)) {
         System.out.println("Entered string is a palindrome");
      } else {
         System.out.println("Entered string is not a palindrome");
      }
   }
}

Output

Enter a string
mam
Original Array[m, a, m]
Reverse Array[m, a, m]
Entered string is a palindrome
raja
Updated on 30-Jul-2019 22:30:20

Advertisements