check if a number is a palindrome in Java
Understanding Palindrome Numbers: A palindrome number reads the same backward as forward. For example, 121 and 1331 are palindromes.
Steps to Check for Palindrome Numbers:
12321
12321 is a palindrome.
public class PalindromeChecker {
public static boolean isPalindrome(int number) {
// Convert number to string
String original = String.valueOf(number);
// Reverse the string
String reversed = new StringBuilder(original).reverse().toString();
// Check if original and reversed strings are equal
return original.equals(reversed);
}
public static void main(String[] args) {
int number = 12321; // Example number to check
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
}
12321 is a palindrome.
isPalindrome(int number) method checks if number is a palindrome.number to a string using String.valueOf(number).StringBuilder to reverse the string representation of number.original) with the reversed string (reversed) using the equals method.import java.util.Scanner; public class PalindromeExample { public static void main(String[] args) { int n, r, sum = 0, temp; Scanner scanner = new Scanner(System.in); System.out.print("Enter the Number: "); n = scanner.nextInt(); // Read the input number temp = n; // Store the original number // Reverse the number while (n > 0) { r = n % 10; // Get the last digit sum = (sum * 10) + r; // Build the reversed number n = n / 10; // Remove the last digit } // Check if the original number and the reversed number are the same if (temp == sum) { System.out.println("Number is Palindrome."); } else { System.out.println("Number is not Palindrome."); } scanner.close(); // Close the scanner } }
n: The input number.r: The remainder when dividing by 10 (the last digit).sum: The reversed number.temp: A temporary variable to store the original number for comparison.while loop, extract the last digit of n using n % 10 and append it to sum.n by removing the last digit (n = n / 10).temp) with the reversed number (sum).First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.