Check Palindrome String
Check whether a string is a palindrome.
BeginnerTopic: Module 4: String Programs
Java Check Palindrome String Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String clean = s.replaceAll("\\s+", "").toLowerCase();
String rev = new StringBuilder(clean).reverse().toString();
if (clean.equals(rev)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
sc.close();
}
}Output
Enter a string: Madam Palindrome
Understanding Check Palindrome String
We normalize case and remove spaces, then compare the string to its reverse.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.