Learn Java 8 Program to Check Whether a Number is Palindrome using Stream API , StringBuilder reverse() method, and anyMatch() with examples.
Code Explanation (Step-by-Step)
• Creates a Scanner object to read user input.
• Creates a stream containing the input number using Stream.of() .
• Converts the number to a string using String.valueOf() and reverses it using the reverse() method of StringBuilder.
• Converts the reversed value back into a string using toString().
• Compares the original and reversed numbers using the equals() method.
• Returns true if both numbers are equal; otherwise,return false.
• Prints whether the number is a palindrome or not.
import java.util.Scanner;
import java.util.stream.Stream;
public class CheckPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int numbers = sc.nextInt();
boolean check = Stream.of(numbers)
.anyMatch(a -> a.equals(
Integer.parseInt(
new StringBuilder(String.valueOf(i))
.reverse()
.toString())));
System.out.println("Is the given number a palindrome? :- " + check);
sc.close();
}
}
Output :
Enter the number
121
Is the given number a palindrome? :- true
Java Program to Check Palindrome Number
import java.util.Scanner;
public class CheckPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int num = sc.nextInt();
String reverse = new StringBuilder(String.valueOf(num))
.reverse()
.toString();
boolean check = String.valueOf(num).equals(reverse);
System.out.println("Given number is palindrome or not: " + check);
sc.close();
}
}
FAQ
What is a palindrome number?
A palindrome number is a number that remains the same when its digits are reversed, such as 121 or 1331.
How do you check a palindrome number in Java?
You can reverse the number and compare it with the original number.
Which Java 8 method is used in this program?
The anyMatch() method from Stream API is used.
Why is StringBuilder used?
StringBuilder.reverse() provides an easy way to reverse digits.
Is 123 a palindrome number?
No, because its reverse is 321.