Google News
logo
Palindrome Program in Java
A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. In Java, we can write a program to check if a given string or number is a palindrome. Here are two examples :

Palindrome program for strings :

Program :
import java.util.Scanner;

public class PalindromeString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        sc.close();

        String reverse = new StringBuilder(str).reverse().toString();

        if (str.equals(reverse)) {
            System.out.println("The string is a palindrome.");
        } else {
            System.out.println("The string is not a palindrome.");
        }
    }
}
Output :
Enter a string: 3553
The string is a palindrome.
Enter a string: abc
The string is not a palindrome.
In this program, we first read a string input from the user using the Scanner class. We then create a StringBuilder object from the input string and use its reverse() method to reverse the string. We convert the reversed string to a String object using the toString() method.

Finally, we use the equals() method to check if the original string is equal to the reversed string. If they are equal, we print a message indicating that the string is a palindrome. Otherwise, we print a message indicating that the string is not a palindrome.

Palindrome program for numbers :

Program :
import java.util.Scanner;

public class PalindromeNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        sc.close();

        int originalNum = num;
        int reverse = 0;

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

        if (originalNum == reverse) {
            System.out.println("The number is a palindrome.");
        } else {
            System.out.println("The number is not a palindrome.");
        }
    }
}
Output :
Enter a number: 3553
The number is a palindrome.
In this program, we first read an integer input from the user using the Scanner class. We then store the original number in a variable called originalNum. We also create a variable called reverse and initialize it to 0.

We then use a while loop to reverse the number. In each iteration of the loop, we extract the last digit of the number using the modulo operator %, and add it to the reverse variable. We then remove the last digit from the number using integer division /.

Finally, we use an if statement to check if the original number is equal to the reversed number. If they are equal, we print a message indicating that the number is a palindrome. Otherwise, we print a message indicating that the number is not a palindrome.