Browse by Domains

Palindrome In Java: How To Check Palindrome Program?

A palindrome is a phrase, word, number, or sequence of characters that reads the same backward and forwards. This blog talks about how to check for a palindrome in Java with the help of a program. Before we learn about palindrome in Java, we will understand the concept of it.

Let’s get started!

What Is Palindrome?

Palindrome refers to a sequence of characters that reads the same forwards and backward.  In the Java palindrome program, palindrome logic checks if a given input string or number remains the same when read from left to right or right to left.

Here is an example of Palindrome

Input: "radar"
Output - Reverse of: "radar" (Reversed: "radar")
Palindrome: YES

Input: "level"
Output - Reverse of: "level" (Reversed: "level")
Palindrome: YES

Input: "12321"
Output - Reverse of: "12321" (Reversed: "12321")
Palindrome: YES

What Is A Palindrome Number?

A palindrome number is a number that remains the same when its digits get reversed. Ex: 15451, for example: If we take 131 and reverse it, then after reversing, the number remains the same.

Steps To Implement A Palindrome Number Program

1. Input The Number From The User- The program starts by taking an input number from the user, typically using the Scanner class in Java.

2. Reverse The Number- The program then reverses the input number’s digits. This can be done using an iterative or recursive approach.

3. Compare The Number With The Original- After reversing the number, the program compares the reversed number with the original number entered by the user.

4. Determine If It’s A Palindrome- If the reversed number is equal to the original number, it is a palindrome. If it is not equal to the original number, it is not a palindrome.

5. Print The Result- If the number is a palindrome, the program prints a message indicating that the number is a palindrome. If the number is not a palindrome, the program prints a message indicating that the number is not a palindrome.

Learn more about palindrome programming with the help of these Java interview questions.

How To Check If a Number Is A Palindrome Number In Java?

The palindrome program in Java has 2 approaches to determining if a number is a palindrome:

  • Iterative Method
  • Recursive Method

Let’s explore each method of the palindrome Java program with practical examples.

1. Iteration Method For Palindrome Number

In the iteration method for checking palindrome numbers, we follow these steps:

1. Start with two variables: ‘nr’ (the original number) and ‘rev’ (initialized to 0).

2. In each iteration:

  • Multiply ‘rev’ by 10 and add the last digit of nr to it.
  • Update ‘nr’ by removing the last digit (equivalent to integer division by 10).

3. Repeat this process until ‘nr’ becomes 0.

4. After the loop, check if ‘rev’ is equal to the original ‘nr’. If they are equal, the number is a palindrome.

Java Code Program

public class PalindromeNumber {
    public static boolean isPalindrome(int num) {
        int originalNum = num;
        int reverse = 0;

        while (num != 0) {
            int lastDigit = num % 10;
            reverse = reverse * 10 + lastDigit;
            num /= 10;
        }

        return originalNum == reverse;
    }

    public static void main(String[] args) {
        int number = 12321;
        if (isPalindrome(number)) {
            System.out.println(number + " is a palindrome number.");
        } else {
            System.out.println(number + " is not a palindrome number.");
        }
    }
}

Output 

12321 is a palindrome number.

Explanation

  • The program defines a function ‘isPalindrome’ that takes an integer as input and returns true if it’s a palindrome number and false otherwise.
  • Inside the function, it initializes ‘originalNum’ with the input number and ‘reverse’ with 0.
  • It then iterates through the number, extracting the last digit, multiplying ‘reverse’ by 10, and adding the last digit, effectively reversing the number.
  • After the loop, it checks if the reversed number (‘reverse’) equals the original number ( ‘originalNum’). If they are equal, it returns true, indicating that the number is a palindrome.

Don’t miss out on the Java knowledge you need – discover the top resources in our comprehensive review: “Top Java Books for Every Programmer

2. Recursion Method for Palindrome Number:

In the recursion method for checking palindrome numbers, we follow these steps:

1. Begin with a recursive function accepting two parameters: the input number ‘n’ and the reversed number ‘rev’.

2. Base case: If ‘n’ is less than 10, return ‘rev’* 10 + n to append the last digit to the reversed number.

3. Recursive case: Obtain the last digit of ‘n’ using ‘n’ % 10, add it to ‘rev’, and recursively invoke the function with n / 10 and the updated ‘rev’.

4. Check if the reversed number ‘rev’ matches the original number ‘n’. If they are equal, the number is a palindrome.

Java Code Program:

public class PalindromeNumber {
    public static boolean isPalindrome(int num) {
        return isPalindromeRecursive(num, 0);
    }

    public static boolean isPalindromeRecursive(int n, int rev) {
        if (n < 10) {
            return rev * 10 + n == n;
        } else {
            int lastDigit = n % 10;
            rev = rev * 10 + lastDigit;
            return isPalindromeRecursive(n / 10, rev);
        }
    }

    public static void main(String[] args) {
        int number = 12321;
        if (isPalindrome(number)) {
            System.out.println(number + " is a palindrome number.");
        } else {
            System.out.println(number + " is not a palindrome number.");
        }
    }
}

Output 

12321 is a palindrome number.

Explanation

  • The program defines a function ‘isPalindrome’ that takes an integer as input and returns true if it’s a palindrome number and false otherwise.
  • Inside the ‘isPalindrome’ function, it calls the recursive function ‘isPalindromeRecursive’ with the input number and initial reversed number 0.
  • The isPalindromeRecursive function handles the recursion:
    1. In the base case, if ‘n’ is less than 10, it checks if ‘rev’ * 10 + ‘n’ equals ‘n’. If they are equal, it returns true, indicating the number is a palindrome.
    2. In the recursive case, it obtains the last digit of ‘n’, adds it to ‘rev’, and recursively calls itself with ‘n’/ 10 and the updated ‘rev’.
  • After the recursion, the main function prints whether the number is a palindrome or not based on the result returned by ‘isPalindrome’.

BigInteger Palindrome Detection

Since standard integer operations can’t handle large numbers, we utilize the ‘BigInteger’ class to circumvent issues like value overflow. 

For ‘BigIntegers’, with a length of log10(n), tasks such as creating, reversing, and checking for palindromes through string operations take log10(n) time.

How To Check Palindrome For BigInteger?

1. Take Input In BigInteger Variable- Accept the input number as a BigInteger variable to handle large numbers.

2. Reverse The Given BigInteger Using The Reverse Method- Utilize the reverse method available in the BigInteger class to reverse the order of digits in the input BigInteger.

3. Compare Both BigIntegers Using The compareTo() Method- Use the compareTo() method to compare the original BigInteger with the reversed BigInteger. If the result is zero, it indicates that both BigIntegers are equal, implying that the number is a palindrome.

An example implementation in Java to check if a BigInteger is a palindrome or not:

import java.math.BigInteger;

public class PalindromeBigInteger {
    public static boolean isPalindrome(BigInteger num) {
        // Reverse the given BigInteger
        BigInteger reversedNum = reverseBigInteger(num);
        
        // Compare both BigIntegers
        return num.compareTo(reversedNum) == 0;
    }

    public static BigInteger reverseBigInteger(BigInteger num) {
        // Convert BigInteger to String for easier manipulation
        String numStr = num.toString();
        
        // Reverse the string
        String reversedStr = new StringBuilder(numStr).reverse().toString();
        
        // Convert the reversed string back to BigInteger
        return new BigInteger(reversedStr);
    }

    public static void main(String[] args) {
        BigInteger number = new BigInteger("123454321");
        
        if (isPalindrome(number)) {
            System.out.println(number + " is a palindrome BigInteger number.");
        } else {
            System.out.println(number + " is not a palindrome BigInteger number.");
        }
    }
}

Output

123454321 is a palindrome BigInteger number.

Explanation

  • The ‘isPalindrome’ method takes a BigInteger as input and returns true if it’s a palindrome BigInteger, false otherwise.
  • Inside ‘isPalindrome’, it first calls the ‘reverseBigInteger’ method to reverse the input BigInteger.
  • The ‘reverseBigInteger’ method converts the BigInteger to a string, reverses the string, and converts it back to a BigInteger.
  • After obtaining the reversed ‘BigInteger’, it compares the original ‘BigInteger’ with the reversed one using the compareTo method. If they are equal, it returns true, indicating that the number is a palindrome.
  • In the main method, we create a ‘BigInteger’ number (123454321) and check if it’s a palindrome using the ‘isPalindrome’ method. Based on the result, it prints whether the number is a palindrome BigInteger or not.

Get certified in Java programming for free!
Enroll in our Free Java Programming Course and accelerate your journey to becoming a Java expert! 

What Is a String Palindrome Number?

A String Palindrome Number in the Java palindrome program refers to a numerical value represented as a string that reads the same forwards and backward. 

While the term may seem contradictory, since a palindrome string in Java inherently contains characters, not numeric values, it essentially entails checking if the string representation of a number forms a palindrome. 

This involves converting the numerical value into a string format, thereby enabling the utilization of string manipulation functions to determine if the sequence remains unchanged when read in reverse.

Explore our detailed guide on ‘Strings In Java‘ for a solid understanding

Example: Checking For Palindrome Numbers in Java

public class StringPalindromeNumber {
    public static boolean isStringPalindrome(String number) {
        // Compare the string with its reverse
        return number.equals(new StringBuilder(number).reverse().toString());
    }

    public static void main(String[] args) {
        String number = "12321";
        
        if (isStringPalindrome(number)) {
            System.out.println(number + " is a string palindrome number.");
        } else {
            System.out.println(number + " is not a string palindrome number.");
        }
    }
}

Output 

12321 is a string palindrome number.

Explanation

  • The ‘isStringPalindrome’ method takes a string representation of a number as input and returns true if it’s a string palindrome number and false otherwise.
  • Inside ‘isStringPalindrome’, which uses a StringBuilder to reverse the input string and then compare it with the original string using the ‘equals’ method.
  • If the original string and its reverse are equal, it returns true, indicating that the number is a string palindrome.
  • In the ‘main’ method, we define a string variable representing a number (12321) and check if it’s a string palindrome using the  ‘isStringPalindrome’ method. Based on the result, it prints whether the number is a string palindrome or not.

Want to learn Java the easy way? 
Get Started with our Beginners friendly blog on “Java Tutorial for Beginners | An Overview of Java

Conclusion

We’ve delved into the Java programming concept of checking for palindromes, a crucial skill for any aspiring Java developer. Understanding how to identify palindromes sharpens your coding abilities and enhances your problem-solving skills. 

Whether a beginner or an advanced learner, mastering palindrome checking in Java is fundamental to your programming journey. 

To deepen your Java expertise and explore advanced software development, consider enrolling in Great Learning’s Free Java Programming and Advance Software Development courses. 

These courses, delivered by industry experts, offer comprehensive insights and hands-on learning experiences to propel your career forward in the dynamic world of programming and software development.

FAQs

How do you handle spaces and punctuation when checking for palindromes in Java?

Typically, spaces and punctuation are ignored when checking for palindromes. You can remove them from the input string before performing the palindrome check.

Can I implement palindrome checking using object-oriented programming principles in Java?

Yes, you can implement palindrome checking in Java using object-oriented programming principles by encapsulating palindrome-related functionality within classes, promoting code reusability and maintainability.

Are there any real-world applications of palindrome checking in Java?

Palindrome checking is used in various applications, such as validating input data (e.g., usernames, passwords), checking for symmetric patterns in strings or numbers, and identifying special sequences in algorithms and data structures.

Can I optimize palindrome checking algorithms using parallel processing or multi-threading in Java?

While it’s theoretically possible to parallelize certain aspects of palindrome checking algorithms, the overhead of managing threads and synchronization may outweigh the benefits, especially for small input sizes. However, parallel processing techniques could be explored for large-scale applications or specialized use cases.

What are some common mistakes or pitfalls to avoid when implementing palindrome checking in Java?

Common mistakes include overlooking edge cases such as empty strings or single-character inputs, incorrect handling of special characters or whitespace, inefficient algorithms resulting in unnecessary computation, and failing to consider language-specific nuances such as character encoding.

Avatar photo
Great Learning
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

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

Post Graduate Programme in Cyber Security

Enroll in the top-rated Cyber Security course in India. Gain hands-on experience and earn a prestigious Post Graduate certificate from Great Lakes

4.64 ★ (1,030 Ratings)

Course Duration : 6 months

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top