Way 1: check whether a string is a palindrome in Java : Using the inbuilt method (StringBuilder)
In Java, you can check whether a string is a palindrome or not by reversing the string and comparing it to the original string. If both the reversed and original strings are equal, then the string is a palindrome. Here is an example code snippet:
public static boolean isPalindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}
In this code, we first create a new StringBuilder
an object from the input string str
. We then call the reverse()
method on the StringBuilder
object to reverse the string and convert it back to a string using the toString()
method. We compare the reversed string to the original string using the equals()
method and return true
if they are equal and false
otherwise.
You can call this method like this:
String str = "racecar";
if (isPalindrome(str)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
In this example, the string "racecar"
is a palindrome, so the output would be:
racecar is a palindrome.
Way 2: check whether a string is a palindrome in Java :Using Recursion
public class Main{
public static boolean checkPalindrome(String input) {
if (input.length() <= 1) {
return true;
}
if (input.charAt(0) != input.charAt(input.length() - 1)) {
return false;
}
return checkPalindrome(input.substring(1, input.length() - 1));
}
public static void main(String[] args) {
System.out.println(checkPalindrome("aka"));
}
}
In the above example, we use recursion to check whether the input string is a palindrome. The base case is when the length of the string is less than or equal to 1, in which case we return true
. If the first and last characters of the string are not the same, we return false
. Otherwise, we recursively call the checkPalindrome
method with the substring that excludes the first and last characters of the string. If all the recursive calls return true
, then the input string is a palindrome.
Way 3: check whether a string is a palindrome in Java : Using Java 8 streams
import java.util.stream.IntStream;
public class Main{
public static boolean checkPalindrome(String input) {
return IntStream.rangeClosed(0, input.length() / 2)
.allMatch(i -> input.charAt(i) == input.charAt(input.length() - i - 1));
}
public static void main(String[] args) {
System.out.println(checkPalindrome("aka"));
}
}
In the above example, we use the IntStream.rangeClosed()
method to generate a stream of integers from 0 to the length of the input string divided by 2. For each integer i in the stream, we check whether the i-th character of the input string is equal to the (length – i – 1)-th character of the input string using the allMatch()
method. If all the characters match, then the input string is a palindrome.
Way 4: check whether a string is a palindrome in Java : Using a loop and a stack
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.stream.IntStream;
public class Main{
public static boolean checkPalindrome(String input) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : input.toCharArray()) {
stack.push(c);
}
StringBuilder reversed = new StringBuilder();
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return input.equals(reversed.toString());
}
public static void main(String[] args) {
System.out.println(checkPalindrome("aka"));
}
}
In the above example, we use a stack to push each character of the input string onto the stack. Then we pop the characters off the stack one by one and append them to a StringBuilder to create the reversed string. Finally, we compare the reversed string with the original input string. If they are the same, then the input string is a palindrome.
Way 5: check whether a string is a palindrome in Java : Multiple Words
To check whether a string (multi-word) is a palindrome or not in Java, you can use the following approach:
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
// Remove all non-alphanumeric characters and convert to lowercase
String cleanedStr = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Compare characters from both ends of the string
int left = 0;
int right = cleanedStr.length() - 1;
while (left < right) {
if (cleanedStr.charAt(left) != cleanedStr.charAt(right)) {
return false; // Characters don't match, not a palindrome
}
left++;
right--;
}
return true; // All characters matched, it's a palindrome
}
public static void main(String[] args) {
//String str = "A man, a plan, a canal, Panama!";
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
if (isPalindrome(str)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
The above program is a Java implementation to check whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
The program consists of a class called PalindromeChecker
. It has a static method isPalindrome
that takes a string as input and returns a boolean value (true
if the string is a palindrome, and false
otherwise).
Here’s a breakdown of the program’s logic:
- The
isPalindrome
the method first cleans the input string by removing all non-alphanumeric characters using thereplaceAll
method and converting the string to lowercase using thetoLowerCase
method. This step ensures case-insensitive palindrome checking. - After cleaning the string, the method initializes two pointers:
left
andright
.left
points to the first character of the cleaned string, andright
points to the last character. - The method enters a loop that continues until
left
is less thanright
. This loop compares characters from both ends of the string, moving inward with each iteration. - Within the loop, if the characters at
left
andright
do not match, it means the string is not a palindrome. In such a case, the method returnsfalse
. - If all characters match (i.e., the loop completes without finding any non-matching characters), the method returns
true
, indicating that the string is a palindrome.
The main
the method serves as an example usage of the isPalindrome
method. It creates a sample string ("A man, a plan, a canal, Panama!"
), calls the isPalindrome
method with this string, and prints a message based on the returned boolean value. In this example, the output will be “The string is a palindrome.”
You can modify the main
method to test different strings for palindromes by passing different values to the isPalindrome
method.
Other Related Assignments:
How to reverse a string in Java?
You can run above all code here just copy and paste.