A palindrome is a word that has the same meaning when read backwards as when read from the front. Examples of palindromes are: Anna, madam, level, racecar and many more.
Mathematics also knows palindromes. Here we talk about palindromes if the numbers do not change when the sequence of numbers is reversed, for example 22 or 141.
The code checks if a number is a palindrome number or not.
A palindrome number is a number which remains the same when its digits are reversed.
Here’s how the code works:
Scanner
class is used to get an input from the user, which is the number to be checked for palindromicity.temp
is initialized with the input number, which is later used for comparison with the reversed number.while
loop, the number is being reversed.
r
.rev
by 10 and adding the value of r
to it.x
is updated by dividing it by 10.while
loop, the value of temp
is compared with rev
to determine if the number is a palindrome or not.
scan.close()
method is used to close the scanner object.import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x, temp, r, rev = 0;
System.out.println("Enter number to check palindrome or not: ");
x = scan.nextInt();
temp = x;
scan.close();
while (x != 0) {
r = x % 10;
rev = rev * 10 + r;
x = x / 10;
}
if (temp == rev) {
System.out.println(temp + " is palindrome number");
} else {
System.out.println(temp + " is not palindrome number");
}
}
}
Enter number to check palindrome or not: 262
262 is palindrome number
Enter number to check palindrome or not: 13
13 is not palindrome number
This Java program checks if a string is a palindrome or not.
reverse
as an empty string and then uses a for loop to reverse the string. The loop iterates over the string starting from the last character, and concatenates each character to the reverse
string.equals
method. If the two strings are equal, it means the original string is a palindrome, and the program prints a message saying so.import java.util.Scanner;
public class PalindromeString {
public static void main(String[] args) {
String str, reverse = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string or number to check palindrome number: ");
str = scan.nextLine();
int length = str.length();
scan.close();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + "isn't a palindrome.");
}
}
}
Enter a string or number to check palindrome number:
madam
madam is a palindrome.