Java Program to check given string is Palindrome or not

In this tutorial, you will learn the writing program for how to check if a string is a palindrome in java .

Read This: What is String Palindrome? Write string palindrome program in C.

How this Java program will behave?

To check String is Palindrome or not?  This Program will take a String as an input. And after applying some logic it will return output as String is Palindrome or not.

For Example: 

Suppose if we give input a string “abba”. This is palindrome String then our program will print “string is palindrome”.

And if we give “abcd” then our program will give “String is not palindrome”.

Java program to check whether a string is palindrome or not

import java.util.*;

public class Main {  
    public static void main(String[] args) {  
        System.out.println("=== Java Program to Check Palindrome String ===\n");

        Scanner sc = new Scanner(System.in);
        System.out.print("Please give First String: ");  
        String str = sc.nextLine();  

        // Normalize the input: remove spaces and convert to lowercase
        String normalized = str.replaceAll("\\s+", "").toLowerCase();

        StringBuilder strRev = new StringBuilder(normalized);
        strRev.reverse(); 

        if(normalized.equals(strRev.toString())) {
            System.out.println("String is a palindrome"); 
        } else {
            System.out.println("String is not a palindrome"); 
        }
    }  
}

Output

=== Java Program to Check Palindrome String ===

Please give First String: Madam
String is a palindrome
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now