Palindrome String in Java — Definition, Examples and Program
A palindrome string is a string that reads the same forward and backward. Palindrome checking is a classic string problem that helps understand loops, indexing, and comparisons.
In this blog, you will learn:
- What a palindrome string is
- Step-by-step examples
- A simple Java program
- Practice challenges
What Is a Palindrome String?
A string is called a palindrome if the characters from left to right are the same as from right to left.
Examples:
- "madam"
- "level"
- "radar"
Non-Palindrome Examples:
- "java"
- "hello"
How the Logic Works
To check whether a string is a palindrome:
- Compare the first and last characters.
- Move inward toward the center.
- If any mismatch occurs, the string is not a palindrome.
Example 1
Input: "LEVEL"
- Compare 'L' and 'L' → match
- Compare 'E' and 'E' → match
- Compare 'V' → middle character
Output: Palindrome String
Example 2
Input: "JAVA"
- Compare 'J' and 'A' → mismatch
Output: Not a Palindrome String
Java Program to Check Palindrome String
import java.util.Scanner;
public class PalindromeString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
boolean isPalindrome = true;
int start = 0;
int end = input.length() - 1;
while (start < end) {
if (input.charAt(start) != input.charAt(end)) {
isPalindrome = false;
break;
}
start++;
end--;
}
if (isPalindrome) {
System.out.println("Palindrome String");
} else {
System.out.println("Not a Palindrome String");
}
}
}
Sample Output
Enter a string: madam
Palindrome String
Enter a string: coding
Not a Palindrome String
Practice Challenges
- Check whether a string is a palindrome without using extra variables.
- Ignore case sensitivity while checking palindrome (e.g., "Madam").
- Check palindrome for a full sentence by ignoring spaces.
Palindrome checking is a common interview question and builds a strong foundation in string manipulation. Once mastered, you can easily solve advanced string problems.