Check Array Palindrome using Java

161
Check Array Palindrome using Java
Advertisement

Check Array Palindrome using Java

Palindromes, sequences that read the same backward as forward, have intrigued minds for centuries. In this guide, we will explore how to check if an array is a palindrome using Java. The provided Java program not only validates palindromic arrays but also unveils the elegance of Java in array manipulation.

Understanding Palindromes:

Palindromes are fascinating patterns that captivate us with their symmetry. Whether in words or numbers, these sequences have a unique property—reading the same from left to right and right to left. Translating this concept to arrays opens up a realm of possibilities for array manipulation in Java.

Checking Palindromes in Arrays

Java
public class PalindromeCheck {
    // Method: Check if an array is a palindrome
    public static boolean isPalindrome(int[] array) {
        int left = 0;
        int right = array.length - 1;

        while (left < right) {
            // Compare elements from both ends of the array
            if (array[left] != array[right]) {
                return false; // Array is not a palindrome
            }
            left++;
            right--;
        }
        return true; // Array is a palindrome
    }

    // Main method: Test array for palindrome
    public static void main(String[] args) {
        // Example array for demonstration
        int[] palindromeArray = {1, 2, 3, 4, 3, 2, 1};

        // Call the isPalindrome method
        boolean isPalindromic = isPalindrome(palindromeArray);

        // Print the result
        if (isPalindromic) {
            System.out.println("The array is a palindrome.");
        } else {
            System.out.println("The array is not a palindrome.");
        }
    }
}

Breaking Down the Implementation:

Method isPalindrome:

  • Declares two pointers (left and right) initialized at the beginning and end of the array.
  • Compares elements at these pointers iteratively until they meet in the middle.
  • If any pair of elements does not match, the method returns false; otherwise, it returns true.

Main Method:

  • Declares an example array (palindromeArray) designed as a palindrome for demonstration.
  • Calls the isPalindrome method, passing the array.
  • Prints the result, indicating whether the array is a palindrome or not.

Output:

Java
// Positive Test
// Input Array {1, 2, 3, 4, 3, 2, 1}
The array is a palindrome.

// Negative Test
// Input Array {1, 2, 3, 4, 5, 2, 1}
The array is not a palindrome.

Learn more about the Array and their manipulation techniques: Array

Conclusion:

This program provides an efficient solution to check if an array is a palindrome. Leveraging pointers and iterative comparison, the method ensures accurate validation of palindromic arrays. Incorporate this approach into your Java projects to unravel the mysteries of array palindromes. Happy coding!

Latest Posts: