- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Program To Check Palindrome String
A palindrome is a sequence of characters that reads the same forward and backward. Common examples include words like "level," "radar," or "racecar." In software development, checking for palindromes is a classic algorithmic challenge often used to test a developer's understanding of string manipulation and loops.
The most efficient way to solve this in Java is by using the Two-Pointer Technique. Instead of creating a copy of the string (which consumes extra memory), we compare characters from both ends and move toward the center.
public class PalindromeChecker {
public static void main(String[] args) {
// You can change this to test different words
String word = "Racecar";
if (isPalindrome(word)) {
System.out.println("The string \"" + word + "\" is a palindrome.");
} else {
System.out.println("The string \"" + word + "\" is not a palindrome.");
}
}
/**
* Checks if a string is a palindrome using the two-pointer approach.
* This method is case-insensitive.
*/
public static boolean isPalindrome(String str) {
// Return true if string is null or empty (based on requirements)
if (str == null || str.isEmpty()) {
return true;
}
// Convert to lowercase to ensure 'M' and 'm' are treated as the same
str = str.toLowerCase();
int left = 0;
int right = str.length() - 1;
// Loop until the pointers meet in the middle
while (left < right) {
// Compare characters at both ends
if (str.charAt(left) != str.charAt(right)) {
return false; // Not a palindrome
}
// Increment left pointer, decrement right pointer
left++;
right--;
}
return true; // Successfully matched all characters
}
}
.toLowerCase() ensures your check is user-friendly and accurate for natural language words.
This program defines a method isPalindrome that checks if the given string is a palindrome by comparing characters from both ends of the string. The main method calls this function with a sample string and prints the result.
How the Logic Works
The two-pointer approach is highly efficient because it has a time complexity of O(n) and a space complexity of O(1) (assuming we don't count the input string itself). Here is the step-by-step logic:
- Initialize Pointers: We set
leftto 0 (the start of the string) andrighttolength - 1(the end of the string). - Comparison: We compare the character at
str.charAt(left)withstr.charAt(right). - Looping: If they match, we move
leftone step forward andrightone step backward. - Early Exit: If at any point the characters don't match, we immediately return
false. - Success: If the pointers meet or cross without a mismatch, the string is a palindrome.
str.replaceAll("[^a-zA-Z0-9]", "").
str.length() returns the total count, but index starts at 0. Always set your right pointer to str.length() - 1 to avoid an IndexOutOfBoundsException.
Practical Real-World Examples
While checking for "madam" is a great exercise, palindrome logic appears in several practical development scenarios:
- Data Integrity: Detecting symmetrical patterns in data streams or DNA sequencing (bioinformatics).
- UI/UX Features: Creating "Undo" logic where a sequence of actions must be reversible or verifiable from both ends.
- Input Validation: Verifying specialized ID formats or serial numbers that follow a mirrored structure for redundancy.
null values. If you call .length() on a null string, your program will crash. Always check if (str == null) at the beginning of your methods.
Alternative Approach: StringBuilder
If you prefer a more concise (though slightly less memory-efficient) method, you can use the StringBuilder class:
public static boolean isPalindromeEasy(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return str.equalsIgnoreCase(reversed);
}
StringBuilder.reverse() method for quick scripts or when performance isn't a critical bottleneck, as it makes the code much easier to read.