Sunday, 5 November 2023

Write a java program to check whether given string is palindrome or not

 

Write a java program to check whether given string is palindrome or not

import java.util.Scanner;

 

public class PalindromeChecker {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter a string to check for palindrome: ");

        String input = scanner.nextLine();

 

        if (isPalindrome(input)) {

            System.out.println("The entered string is a palindrome.");

        } else {

            System.out.println("The entered string is not a palindrome.");

        }

    }

 

    public static boolean isPalindrome(String str) {

        str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to lowercase

        int left = 0;

        int right = str.length() - 1;

 

        while (left < right) {

            if (str.charAt(left) != str.charAt(right)) {

                return false;

            }

            left++;

            right--;

        }

 

        return true;

    }

}