Palindrome String in Java
A palindrome is a string that reads the same forward and backward. In this post, you'll learn how to write a Java program to check if a string is a palindrome.
What is a Palindrome?
Examples of palindrome strings include:
- madam
- racecar
- level
- radar
Java Program to Check Palindrome
import java.util.Scanner; public class PalindromeCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); String reversed = new StringBuilder(input).reverse().toString(); if (input.equalsIgnoreCase(reversed)) { System.out.println(input + " is a palindrome."); } else { System.out.println(input + " is not a palindrome."); } } }
Output
Enter a string: radar radar is a palindrome.
Explanation
- We use
StringBuilder
to reverse the string. - Then we compare the original and reversed string using
equalsIgnoreCase
. - If both match, it’s a palindrome.
Conclusion
This simple Java program demonstrates how to check for palindromes — a common interview question and a great exercise in working with strings.