To Check String Palindrome in Java

Yuvaraj
4 min readAug 9, 2024

--

Basic Java Program

A string palindrome is a word, phrase, or sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization.

Example:

  • “madam”: If you read it from left to right (forward) and from right to left (backward), it remains “madam.” So, it’s a palindrome.
  • “racecar”: Reading it forward and backward gives the same word, so it’s a palindrome.
  • “A man a plan a canal Panama”: If you remove the spaces and ignore the case, it reads the same forward and backward, so it’s a palindrome.

Non-Example:

  • “hello”: If you read it backward, it becomes “olleh,” which is different from “hello,” so it’s not a palindrome.

Why It Matters:

Palindromes are often used in coding problems to test string manipulation skills. The concept is also interesting in mathematics, literature, and puzzles. For instance, palindromic numbers like 121 or 1331 are the same when reversed.

// Online Java Compiler
// Use this editor to write, compile and run your Java code online

import java.util.Scanner;

public class SimplePalindromeChecker {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input a string from the user
System.out.print("Enter a string: ");
String input = scanner.nextLine();

// Reverse the string
String reversed = new StringBuilder(input).reverse().toString();

// Check if the original string is equal to the reversed string
if (input.equalsIgnoreCase(reversed)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}

scanner.close();
}
}


// Output:

/* Enter a string: madam
madam is a palindrome. */

Explanation:

  1. Input: The program asks the user to enter a string.
  2. Reverse: It reverses the string using StringBuilder.
  3. Comparison: It compares the original string with the reversed string using equalsIgnoreCase to ignore case differences.
  4. Output: The program prints whether the input string is a palindrome.

This approach directly compares the original string with its reversed version, making it straightforward and easy to understand.

Method 2

import java.util.Scanner;

public class PalindromeChecker {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input a string from the user
System.out.print("Enter a string: ");
String input = scanner.nextLine();

// Check if the string is a palindrome
if (isPalindrome(input)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}

scanner.close();
}

// Method to check if a string is a palindrome
public static boolean isPalindrome(String str) {
// Remove any spaces and convert to lowercase for case-insensitive comparison
str = str.replaceAll("\\s", "").toLowerCase();

int start = 0;
int end = str.length() - 1;

// Compare characters from start and end towards the middle
while (start < end) {
if (str.charAt(start) != str.charAt(end)) {
return false; // If characters don't match, it's not a palindrome
}
start++;
end--;
}

return true; // If all characters match, it's a palindrome
}
}

Overview

This method, isPalindrome, checks whether a given string is a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forward.

Code Breakdown

public static boolean isPalindrome(String str) {
// Remove any spaces and convert to lowercase for case-insensitive comparison
str = str.replaceAll("\\s", "").toLowerCase();

Removing Spaces and Converting to Lowercase:

  • str.replaceAll("\\s", ""): This removes all spaces from the string. The \\s is a regular expression that matches any whitespace character (like spaces).
  • .toLowerCase(): This converts the entire string to lowercase so that the comparison is not case-sensitive. For example, "Madam" becomes "madam".

After this step, the string is ready for comparison without worrying about spaces or uppercase letters.

    int start = 0;
int end = str.length() - 1;

Setting Up Start and End Points:

  • start: This is an index that starts from the beginning of the string (0).
  • end: This is an index that starts from the end of the string (str.length() - 1).

These two pointers will be used to compare characters from the start and end of the string moving towards the middle.

    while (start < end) {
if (str.charAt(start) != str.charAt(end)) {
return false; // If characters don't match, it's not a palindrome
}
start++;
end--;
}

Comparing Characters:

  • while (start < end): This loop continues as long as the start index is less than the end index.
  • str.charAt(start) != str.charAt(end): The charAt method is used to get the character at the start and end positions. If these characters are not the same, the string is not a palindrome, so the method returns false.
  • If the characters are the same, the start index is moved one step forward (start++), and the end index is moved one step backward (end--). This continues until the entire string has been checked.
    return true; // If all characters match, it's a palindrome
}

Returning the Result:

  • If the loop completes without finding any mismatched characters, it means all the characters matched, so the string is a palindrome. The method then returns true.

Example Walkthrough

Let’s say the input string is "Racecar".

  1. After removing spaces and converting to lowercase, the string becomes "racecar".
  2. start points to 'r' (first character) and end points to 'r' (last character).
  3. The characters are the same, so the pointers move inward: start now points to 'a' and end points to 'a'.
  4. This process continues until all characters are checked.
  5. Since all characters match, the method returns true, indicating that "Racecar" is a palindrome.

In Short:

  • The program prepares the string by removing spaces and converting it to lowercase.
  • It then compares characters from the start and end of the string, moving towards the middle.
  • If all characters match, the string is a palindrome. If any characters don’t match, it’s not.
  • Time Complexity: O(n)
  • Space Complexity: O(n)

This means that both the time and space requirements scale linearly with the length of the input string.

--

--