HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Puzzles / Java string palindrome – Java number palindrome example

Java string palindrome – Java number palindrome example

A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, generally if used comma, separators or other word dividers are ignored. [Not mandatory]

Similarly, palindrome numbers are those numbers which represent same number if all digits are reversed (Underscores can be ignored in large numbers such as 1_00_00_001). Underscores in numeric literals are new addition in Java 7 features.

1. Java palindrome string example

To check palindrome string, reverse the String characters. Now use String.equals() method to verify if given string was palindrome or not.

1.1. Check string palindrome using Apache commons StringUtils

Simple palindrome program in Java for string. It is also palindrome program in java using reverse method.

public class Main 
{
    public static void main(String[] args) 
    {
        System.out.println( isPalindromeString("howtodoinjava") );		//false
        System.out.println( isPalindromeString("abcba") );				//true
    }
    
    public static boolean isPalindromeString(String originalString) 
    {
        String reverse = StringUtils.reverse(originalString);
        return originalString.equals(reverse);
    }
}

1.2. Check string palindrome using StringBuilder

This same logic can be applied with StringBuffer class as well.

public class Main 
{
    public static void main(String[] args) 
    {
        System.out.println( isPalindromeString("howtodoinjava") );
        System.out.println( isPalindromeString("abcba") );
    }
    
    public static boolean isPalindromeString(String originalString) 
    {
        String reverse = new StringBuilder(originalString).reverse().toString();
        return originalString.equals(reverse);
    }
}

1.3. Check string palindrome with for loop

Use for loop to get the reverse string by iterating over string characters from last index using charAt() method and create new string.

Use this approach only when you are checking string palindrome in java without using reverse method.

public class Main 
{
    public static void main(String[] args) 
    {
        System.out.println( isPalindromeString("howtodoinjava") );
        System.out.println( isPalindromeString("abcba") );
    }
    
    public static boolean isPalindromeString(String originalString) 
    {
        String reverse = "";
        
        int length = originalString.length();
        
        for ( int i = length - 1; i >= 0; i-- )
            reverse = reverse + originalString.charAt(i);
        
        return originalString.equals(reverse);
    }
}

2. Java palindrome number example

To verify, if a given number is palindrome number is or not, we need to reverse the digits in number and compare with original number if both are equal or not.

package com.howtodoinjava.puzzle;

public class PalindromeTest
{
    /**
     * Test the actual code if it works correctly
     * */
    public static void main(String[] args)
    {
        System.out.println(checkIntegerPalindrome( 100 )); 		//false
        System.out.println(checkIntegerPalindrome( 101 )); 		//true
        System.out.println(checkIntegerPalindrome( 500045 )); 	//false
        System.out.println(checkIntegerPalindrome( 50005 )); 	//true
    }

    /**
     * This function will test the equality if a number and its reverse.
     * @return true if number is palindrome else false
     * */
    public static boolean checkIntegerPalindrome(int number)
    {
        boolean isPalindrome = false;
        if(number == reverse(number))
        {
            isPalindrome = true;
        }
        return isPalindrome;
    }

    /**
     * This function will reverse a given number.
     * @return reverse number
     * */
    public static int reverse(int number)
    {
        int reverse = 0;
        int remainder = 0;
        do {
            remainder = number % 10;
            reverse = reverse * 10 + remainder;
            number = number / 10;

        } while (number > 0);
        return reverse;
    }
}


Program Output.


false
true
false
true

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Pallavi

    October 22, 2018

    Hi Lokesh,

    Can you please explain a program to find the longest substring palindrome.

  2. mvimal678

    July 25, 2014

    class A
    {
    int v;
    A()
    {
    calc();
    }
    public void calc()
    {
    System.out.println(“A class Method “);
    }
    }
    class B extends A
    {
    B()
    {
    calc();
    }
    public void calc()
    {
    System.out.println(“B class Method “);
    }
    public static void main(String ar[])
    {
    A a1 = new B();
    }
    }

    output

    B class Method
    B class Method

    calc() method in A class is why not executed in A class Constuctor or why execute calc() method of B class
    sir plz solve my problem

    • Lokesh Gupta

      July 25, 2014

      Because you have override the method. Any method called is always first looked upon class which instance is being created. If not found there, ONLY then super class is looked upon. In both constructor calls, calc() method is found in B so JVM does not go beyond that i.e. A is not looked into.

      • ss

        November 8, 2014

        We can easily do this in java using StringBuilder /StringBuffer also.

        StringBuilder str = new StringBuilder(“malayalam”);
        System.out.println(“reverse = ” + str.reverse());

        then compare original string and reversed one

        • Lokesh Gupta

          November 11, 2014

          Good example. You are right. We can use above method as well.

          • andy

            February 14, 2016

            I have to say, the following code doesn’t seem written by someone with 8 Years of rich experience in java technology. Very bad code.

             
            public static boolean checkIntegerPalindrome(int number)
                {
                    boolean isPalindrome = false;
                    if(number == reverse(number))
                    {
                        isPalindrome = true;
                    }
                    return isPalindrome;
                }
            
            • Lokesh Gupta

              February 14, 2016

              Please suggest the good way..

            • javaist

              December 28, 2017

              Andy, why won’t you just code:
              public static boolean checkIntegerPalindrome(int number) {
              return number == reverse number;
              }
              ??

              • Rajesh G

                May 9, 2018

                It should be reverse(number);

                public static boolean checkIntegerPalindrome(int number)
                {
                return number == reverse(number);
                }

Comments are closed on this article!

Search Tutorials

Java Puzzles

  • Interview Puzzles List
  • Dead vs Unreachable Code
  • Palindrome Number
  • Detect infinite loop in LinkedList
  • [i += j] Vs [i = i + j]
  • HiLo Guessing Game
  • Find All Distinct Duplicate Elements
  • TreeMap Put Operation
  • String With Nth Longest Length
  • Good String Vs Bad String
  • Complete String
  • Reverse String
  • Calculate Factorial
  • FizzBuzz Solution
  • Find Missing Number From Series
  • Create Instance Without New Keyword

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces