Examples
- Leap Year Program in Java (Check Leap Year or Not)
- Check Number is Positive or Negative in Java (4 Ways)
- Java Program to Check Character is Alphabet or Not
- Armstrong Number Program in Java (for loop, Recursion)
- Print Prime Numbers Between 1 to N in Java (1 to 100)
- Java Program for Palindrome Number (Palindrome Code)
- Sum of n Natural Numbers in Java (Programs & Explanation)
- Java Multiplication Table Program (Loops, 2D Array) 5 Ways
- Find GCD of Two Numbers in Java (HCF Program)
- GCD of Three Numbers in Java (HCF of 3 Numbers Program
- GCD of Array in Java (GCD of n Numbers Program)
- LCM of Two Numbers in Java (LCM Program and Code)
- LCM of Three Numbers in Java (Easy Programs)
- LCM of n Numbers in Java (LCM of Array of Numbers)
- How to Print A to Z in Java? 3 Ways to Print Alphabets
Java Program for Palindrome Number (Palindrome Code)
Palindrome numbers are a fascinating mathematical concept that has intrigued mathematicians and computer scientists for decades. These special numbers possess a unique property: they read the same forwards and backwards.
Palindrome numbers are not only an interesting mathematical curiosity but also find practical applications in various programming scenarios.
What is Palindrome Number in Java?
A palindrome number is a numerical value that remains unchanged when its digits are reversed.
For example, 121, 1331, and 12321 are all palindrome numbers because they read the same from left to right as they do from right to left.
Use Cases of Palindrome Numbers
Palindrome numbers have several real-world applications across different domains:
-
Number Manipulation: Palindromes are often used in various mathematical operations, such as finding the closest palindrome to a given number or generating sequences of palindromic numbers.
-
Data Validation: Palindromes can be used in data validation scenarios, where ensuring the integrity of data is crucial. For example, credit card numbers and identification numbers often use palindromic patterns as part of their validation algorithms.
-
Programming Challenges: Palindrome numbers serve as interesting challenges for programmers. They require creative solutions and can help developers enhance their problem-solving skills.
-
String Manipulation: Palindrome concepts can also be applied to strings, making them relevant in text processing and algorithmic tasks involving string reversal and symmetry.
Throughout this tutorial, we will learn the different programs for palindrome number in Java. Let’s get started!
Concepts to Learn:
Java Program for Palindrome Number Using while Loop
Here's a program to check if a number is a palindrome in Java using a while loop. We will check if a given number remains the same when its digits are reversed:
Code
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
int originalNumber = number;
int reversedNumber = 0;
while (number != 0) {
int remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}
}
}
Output
Enter a number: 121
121 is a palindrome.
Explanation
-
The program takes an integer input from the user (in this case, 121).
-
It initializes two variables: originalNumber to store the original input and reversedNumber to store the reversed version of the number, initially set to 0.
-
It enters a while loop where it repeatedly extracts the last digit of the number, adds it to reversedNumber (after shifting its digits one place to the left), and removes the last digit from number until number becomes 0. This effectively reverses the digits of the input number.
-
After the loop, it compares the originalNumber with the reversedNumber. If they are equal, it prints that the input number is a palindrome; otherwise, it prints that it is not a palindrome.
Palindrome Number in Java Using for Loop
Here is the palindrome code in Java using for loop:
Code
import java.util.Scanner;
public class PalindromeNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
public static boolean isPalindrome(int number) {
int originalNumber = number;
int reversedNumber = 0;
// Reverse the number using a for loop
while (number > 0) {
int lastDigit = number % 10;
reversedNumber = reversedNumber * 10 + lastDigit;
number /= 10;
}
// Check if the reversed number is equal to the original number
return originalNumber == reversedNumber;
}
}
Output
Enter a number: 121
121 is a palindrome.
Explanation
-
We start by importing the Scanner class to read input from the user.
-
We create a main method where the program execution begins.
-
The isPalindrome method takes an integer as input and returns true if it's a palindrome, and false otherwise.
-
After the loop, we compare originalNumber with reversedNumber to check if they are equal. If they are equal, the number is a palindrome, and the method returns true. Otherwise, it returns false.
-
In the main method, we print whether the number is a palindrome or not based on the result from the isPalindrome method.
Program for Palindrome Number in Java Using Scanner
Here's a Java program to check if a number is a palindrome using another method, which involves converting the number to a string and comparing it with its reverse:
Code
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
String originalString = Integer.toString(number);
String reversedString = new StringBuilder(originalString).reverse().toString();
if (originalString.equals(reversedString)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
}
Output
Enter a number: 12321
12321 is a palindrome.
Explanation
-
The program takes an integer input from the user (in this case, 12321).
-
It converts the integer to a string using Integer.toString(), creating originalString.
-
It then uses a StringBuilder to reverse originalString, creating reversedString.
-
Finally, it compares originalString and reversedString using the equals() method. If they are equal, it prints that the input number is a palindrome; otherwise, it prints that it is not a palindrome.
Check Palindrome Number in Java Using Recursion
Here's a Java program to check if a number is a palindrome using recursion:
Code
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
public static boolean isPalindrome(int number) {
return isPalindromeHelper(number, 0);
}
private static boolean isPalindromeHelper(int remainingNumber, int reversedNumber) {
if (remainingNumber == 0) {
return number == reversedNumber;
}
int lastDigit = remainingNumber % 10;
reversedNumber = reversedNumber * 10 + lastDigit;
return isPalindromeHelper(remainingNumber / 10, reversedNumber);
}
}
Output
Enter a number: 1221
1221 is a palindrome.
Explanation
-
The program takes an integer input from the user (in this case, 1221).
-
It calls the isPalindrome() method to check if the input number is a palindrome.
-
The isPalindrome() method is a wrapper method that calls the recursive helper method isPalindromeHelper(). It passes the original number and an initial reversed number of 0.
-
The isPalindromeHelper() method is a recursive function that performs the actual palindrome check. It checks if the remainingNumber (the portion of the number yet to be processed) is 0. If it is, it compares the number with the reversedNumber to determine if it's a palindrome.
-
If the remainingNumber is not 0, the function extracts the last digit from the remainingNumber, appends it to the reversedNumber, and continues the recursion by dividing remainingNumber by 10 to remove the last digit.
Java Program for Palindrome String
Here's a Java program to check if a string is a palindrome:
Code
import java.util.Scanner;
public class PalindromeStringCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine().toLowerCase(); // Convert to lowercase for case-insensitive comparison
scanner.close();
if (isPalindrome(inputString)) {
System.out.println(inputString + " is a palindrome.");
} else {
System.out.println(inputString + " is not a palindrome.");
}
}
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Output
Enter a string: racecar
racecar is a palindrome.
Explanation
-
The program takes a string input from the user (in this case, "racecar").
-
It converts the input string to lowercase using .toLowerCase() to make the comparison case-insensitive.
-
It calls the isPalindrome() method to check if the input string is a palindrome.
-
The isPalindrome() method uses two pointers, left and right, initialized to the start and end of the string, respectively.
-
It enters a while loop that continues as long as left is less than right. In each iteration, it compares the characters at positions left and right. If they are not equal, the function returns false because the string is not a palindrome. Otherwise, it increments left and decrements right to continue checking the next pair of characters.
-
If the loop completes without finding any unequal pairs, the function returns true, indicating that the string is a palindrome.
Learn Next: