Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

String Palindrome Program in Java

Last Updated on May 18, 2023 by Prepbytes

A string palindrome program in Java is a string that reads the same forwards and backwards. Creating a program to check if a given string is a palindrome is a common programming exercise. In this program, we aim to determine whether a given string is a palindrome or not. The program takes a string as input from the user or from a predefined string variable. It then compares the characters from both ends of the string, moving towards the center, to check if they are equal.

What is a String Palindrome?

A string is considered to be a palindrome if it remains unaltered whether it is read from left to right or right to left. The next step is to establish whether the string "str"’s reverse string is the same as it is. So let’s look at the string "str."

Example:

Input : str = "abba" 
Output: Yes

Input : str = "abcd"
Output: No 

Algorithm to Find the String Palindrome in Java:

  • START
  • Take input from the user or initialize it manually (string).
  • Check if the length is equal to zero or one
    • Print it is a palindrome.
  • Check each character in substring from the front and rear; if found, equal
    • Print it is a palindrome
  • If steps 3 and 4 fail
    • Print it is not Palindrome
  • END

Naive Approach: We can determine whether a given string is a palindrome by comparing the original string to its reversed form.
Below is the implementation:

String Palindrome Java Program

import java.io.*;

class PrepBuddy {
    public static boolean isPalindrome(String str)
    {
        String rev = "";

        boolean ans = false;

        for (int i = str.length() - 1; i >= 0; i--) {
            rev = rev + str.charAt(i);
        }

        if (str.equals(rev)) {
            ans = true;
        }
        return ans;
    }
    public static void main(String[] args)
    {
        String str = "Abcd";

        str = str.toLowerCase();
        boolean A = isPalindrome(str);
        System.out.println(A);
    }
}

Output:

False

In the previous example, if we substitute ABba for abba, the output should be yes. As a result, before we check for a palindrome, we must alter the case of the string to either lowercase or uppercase. We will obtain surprising outcomes if we do not do this. This is due to the fact that the compiler validates the characters based on their ASCII value, and A’s ASCII value is not the same as a’s.

String Palindrome Optimized Approach

Our strategy will be to first transform the string to lowercase. Then we’ll take two pointers, i pointing to the beginning of the string and j pointing to the end. Continue to increase i and decrease j while I < j and verify whether the characters at these addresses are the same or not at each step. If not, the string is not a palindrome otherwise, it is.

class PrepBytes {

    static boolean isPalindrome(String str)
    {

        int i = 0, j = str.length() - 1;

        while (i < j) {

            if (str.charAt(i) != str.charAt(j))
                return false;

            i++;
            j--;
        }

        return true;
    }

    public static void main(String[] args)
    {
        String str = "abba";

        str = str.toLowerCase();
        if (isPalindrome(str))

            System.out.print("Yes");
        else

            System.out.print("No");
    }
}

Output:

Yes

String Palindrome Recursive Approach

The strategy is straightforward. We will examine the first and last values of the string using recursion, as we did with the two-pointer technique.

  • We'll use two pointers, i pointing to the beginning of the string and j pointing to the end.
  • Continue to increase i and decrease j while I =j condition is satisfied, print true, otherwise, print false.
    Below is the implementation:
import java.io.*;
class PrepBytes {
    public static boolean isPalindrome(int i, int j,
                                    String A)
    {
        if (i >= j) {
            return true;
        }

        if (A.charAt(i) != A.charAt(j)) {
            return false;
        }

        return isPalindrome(i + 1, j - 1, A);
    }

    public static boolean isPalindrome(String A)
    {
        return isPalindrome(0, A.length() - 1, A);
    }

    public static void main(String[] args)
    {
        String A = "PrepBytes";

        A = A.toLowerCase();
        boolean str = isPalindrome(A);
        System.out.println(str);
    }
}

Output:

No

Conclusion
In conclusion, the String Palindrome Program in java allows us to determine whether a given string is a palindrome or not. By comparing the characters from both ends of the string and checking for equality, we can determine if the string reads the same forwards and backwards. This program provides an opportunity to practice string manipulation, iteration, and conditional statements in programming languages like C++, Python, or Java.

Frequently Asked Questions

Q1. Can I use built-in functions in Java to check for a palindrome?
Ans. Yes, Java provides built-in functions that can help check if a string is a palindrome. You can use the StringBuilder class to reverse the string and then compare it with the original string using the equals() method. Here’s an example:

String original = "madam";
StringBuilder reversed = new StringBuilder(original).reverse();
boolean isPalindrome = original.equals(reversed.toString());
The equals() method compares the contents of the two strings for equality.

Q2. How can I handle spaces and punctuation when checking for a palindrome in Java?
Ans. To handle spaces and punctuation when checking for a palindrome in Java, you can remove them from the string before performing the comparison. One approach is to use regular expressions to replace all non-alphanumeric characters with an empty string. Here’s an example:

String original = "A man, a plan, a canal: Panama!";
String cleaned = original.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

In this example, the replaceAll() method replaces all characters that are not letters or digits with an empty string. The resulting cleaned string is then ready for the palindrome check.

Q3. Can a sentence or phrase be considered a palindrome in Java?
Ans. Yes, a sentence or phrase can be considered a palindrome in Java if it reads the same forwards and backwards, ignoring spaces, punctuation, and case. You can apply the necessary transformations, such as removing spaces and punctuation and converting to lowercase or uppercase, before checking for the palindrome condition.

Q4. How can I efficiently check if a very long string is a palindrome in Java?
Ans. To efficiently check if a very long string is a palindrome in Java, you can use the two-pointer approach mentioned earlier. By comparing the characters at corresponding positions from both ends, you can determine if the string is a palindrome without the need for extra memory or time-consuming operations. This approach has a time complexity of O(N/2), where N is the length of the string.

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java
Linked List Program in Java
String Programs in Java
Star Program in Java
Number Pattern Program in Java
For Loop Program In Java
Pattern Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *