📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
A palindrome number remains the same when its digits are reversed. Checking whether a number is a palindrome is a common problem in computer science, often used to introduce the concepts of string manipulation and numerical analysis. This blog post will explain how to write a Java program to check if a given number is a palindrome.
2. Program Steps
1. Read a number from the user.
2. Store the original number to compare later.
3. Reverse the number.
4. Compare the reversed number with the original number.
5. Display whether the number is a palindrome.
6. Close the Scanner object to avoid resource leaks.
3. Code Program
import java.util.Scanner;
public class PalindromeNumberChecker {
public static void main(String[] args) {
// Creating a Scanner object for reading input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scanner.nextInt();
// Storing the original number for comparison
int originalNumber = number;
// Reversing the number
int reversedNumber = 0;
while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
// Checking if the number is a palindrome
if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome number.");
} else {
System.out.println(originalNumber + " is not a palindrome number.");
}
scanner.close(); // Closing the scanner
}
}
Output:
Enter a number: 121 121 is a palindrome number.
Explanation:
1. The program begins by creating a Scanner object to read the user's input.
2. The user is prompted to enter a number, which is stored in the variable number.
3. The original number is saved in originalNumber for later comparison. This is important because the number will be altered during the reversal process.
4. The program then reverses the number using a while loop. Inside the loop, it extracts the last digit of number (number % 10), adds it to reversedNumber, and then removes the last digit from number (number /= 10).
5. After reversing, it checks if reversedNumber is equal to originalNumber. If they are equal, the number is a palindrome; otherwise, it is not.
6. The program outputs the result, informing the user whether the entered number is a palindrome.
7. Finally, the Scanner object is closed to prevent resource leaks, following best practices for handling user input in Java.
Comments
Post a Comment
Leave Comment