🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Checking if a string is a palindrome is a common task in text processing. In this blog post, we will explore various methods to check if an input string is a palindrome in Java.
Table of Contents
- Using a Simple Loop
- Using StringBuilder's
reverse()Method - Using Java 8 Streams
- Complete Example Program
- Conclusion
1. Using a Simple Loop
One of the simplest methods to check if a string is a palindrome is by comparing characters from the start and end of the string moving towards the center.
Example:
public class PalindromeCheckUsingLoop {
public static void main(String[] args) {
String input = "Madam";
boolean result = isPalindrome(input);
System.out.println("Is the string \"" + input + "\" a palindrome? " + result);
}
public static boolean isPalindrome(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Output:
Is the string "Madam" a palindrome? true
Explanation:
- The string is converted to lowercase and all non-alphanumeric characters are removed to normalize the input.
- A loop is used to compare characters from the start and end of the string moving towards the center.
- If any characters do not match, the string is not a palindrome.
2. Using StringBuilder's reverse()() Method
Another method to check if a string is a palindrome is by reversing the string and comparing it to the original string.
Example:
public class PalindromeCheckUsingStringBuilder {
public static void main(String[] args) {
String input = "Madam";
boolean result = isPalindrome(input);
System.out.println("Is the string \"" + input + "\" a palindrome? " + result);
}
public static boolean isPalindrome(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
String reversedStr = new StringBuilder(str).reverse().toString();
return str.equals(reversedStr);
}
}
Output:
Is the string "Madam" a palindrome? true
Explanation:
- The string is normalized by converting it to lowercase and removing non-alphanumeric characters.
- The
StringBuilder'sreverse()method is used to reverse the string. - The reversed string is compared to the original string to determine if it is a palindrome.
3. Using Java 8 Streams
Java 8 Streams provide a modern and concise way to check if a string is a palindrome.
Example:
import java.util.stream.IntStream;
public class PalindromeCheckUsingStreams {
public static void main(String[] args) {
String input = "Madam";
boolean result = isPalindrome(input);
System.out.println("Is the string \"" + input + "\" a palindrome? " + result);
}
public static boolean isPalindrome(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
return IntStream.range(0, str.length() / 2)
.allMatch(i -> str.charAt(i) == str.charAt(str.length() - i - 1));
}
}
Output:
Is the string "Madam" a palindrome? true
Explanation:
- The string is normalized by converting it to lowercase and removing non-alphanumeric characters.
- An
IntStreamis used to iterate over the first half of the string. - The
allMatch()method checks if all characters from the start and end of the string match.
4. Complete Example Program
Here is a complete program that demonstrates all the methods discussed above to check if a string is a palindrome.
Example Code:
import java.util.stream.IntStream;
public class PalindromeCheckExample {
public static void main(String[] args) {
String input = "A man, a plan, a canal, Panama";
// Using a Simple Loop
boolean resultLoop = isPalindromeUsingLoop(input);
System.out.println("Using Simple Loop:");
System.out.println("Is the string \"" + input + "\" a palindrome? " + resultLoop);
// Using StringBuilder's reverse() Method
boolean resultStringBuilder = isPalindromeUsingStringBuilder(input);
System.out.println("\nUsing StringBuilder's reverse() Method:");
System.out.println("Is the string \"" + input + "\" a palindrome? " + resultStringBuilder);
// Using Java 8 Streams
boolean resultStreams = isPalindromeUsingStreams(input);
System.out.println("\nUsing Java 8 Streams:");
System.out.println("Is the string \"" + input + "\" a palindrome? " + resultStreams);
}
public static boolean isPalindromeUsingLoop(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static boolean isPalindromeUsingStringBuilder(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
String reversedStr = new StringBuilder(str).reverse().toString();
return str.equals(reversedStr);
}
public static boolean isPalindromeUsingStreams(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
return IntStream.range(0, str.length() / 2)
.allMatch(i -> str.charAt(i) == str.charAt(str.length() - i - 1));
}
}
Output:
Using Simple Loop:
Is the string "A man, a plan, a canal, Panama" a palindrome? true
Using StringBuilder's reverse() Method:
Is the string "A man, a plan, a canal, Panama" a palindrome? true
Using Java 8 Streams:
Is the string "A man, a plan, a canal, Panama" a palindrome? true
5. Conclusion
Checking if a string is a palindrome can be accomplished in multiple ways in Java. The simple loop method is straightforward and easy to understand, while the StringBuilder's reverse() method provides a quick and concise solution. Java 8 Streams offer a modern, functional programming approach to the same problem.
By understanding these different methods, you can choose the one that best fits your needs and coding style. Happy coding!
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment