How to check if a given string is a palindrome

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: ");
        String input = scanner.nextLine();
        boolean isPalindrome = checkPalindrome(input);
        System.out.println(input + " is " + (isPalindrome ? "a palindrome" : "not a palindrome"));
        scanner.close();
    }

    private static boolean checkPalindrome(String str) {
        String reversed = new StringBuilder(str).reverse().toString();
        return str.equals(reversed);
    }
}

 

Post your Answer