Java Project - Palindrome Number Checker
How to Check if a Number Is a Palindrome in Java:
Palindrome Number:
Input: A number.
Output: Whether the number is a palindrome or not.
Example:
- Input: 121
- Output: "121 is a palindrome."
- Input: 123
- Output: "123 is not a palindrome."
Solution 1: Palindrome Number using Loops
Code:
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
// Create a scanner for user input
Scanner scanner = new Scanner(System.in);
// Input number
System.out.println("Enter a number: ");
int number = scanner.nextInt();
// Initialize variables to reverse the number
int originalNumber = number;
int reversedNumber = 0;
// Reverse the number using a loop
while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
// Check if the original number is the same as the reversed number
if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}
scanner.close();
}
}
Output:
Enter a number: 1221 1221 is a palindrome
Enter a number: 1122 1122 is not a palindrome.
Explanation :
- The program reads a number from the user and stores it in a variable.
- It reverses the number by extracting digits one by one.
- It checks if the reversed number is the same as the original and prints whether it is a palindrome.
Solution 2: Palindrome Number using StringBuilder
Code:
import java.util.Scanner;
public class PalindromeNumberStringBuilder {
public static void main(String[] args) {
// Create a scanner for user input
Scanner scanner = new Scanner(System.in);
// Input number
System.out.println("Enter a number: ");
String number = scanner.nextLine();
// Reverse the number using StringBuilder
String reversedNumber = new StringBuilder(number).reverse().toString();
// Check if the original number is the same as the reversed number
if (number.equals(reversedNumber)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
scanner.close();
}
}
Output:
Enter a number: 4444 4444 is a palindrome.
Enter a number: 899998 899998 is a palindrome.
Explanation:
- This solution reads the number as a string.
- It uses the StringBuilder class to reverse the string representation of the number.
- The program compares the original string with the reversed one and prints whether it is a palindrome.
Java Code Editor:
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/projects/java/java-project-palindrome-number-checker.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics