Java program to check for Palindrome.
What is a palindrome number or palindrome string? There are following definitions:
- A palindrome number or a palindrome string is one whose mirror image is same as itself.
- A Palindrome is exactly same as seen from beginning or ending.
Concept used here:
if(s.charAt(i) == s.charAt(l-i-1);
s.charAt(0) =M (first character)
s.charAt(l-1-0) =M (last character)
Now check for ‘A’ –
A is the second character in the string – Check if it is also the second last character.
D is the third character in the string – Check if it is also the third last character in the string.
public static void main(String args)
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number or String : ");
s=sc.nextLine(); // Reading the whole line as string.
l=s.length(); // finding the length of the string.
while(i<l/2) // Number of iterations are half because we check the first and last element thus iteration ends with middle element
if(s.charAt(i)!=s.charAt(l-i-1)) // check if first character matches the last character or not
count++; // if any character does not matches then increase the counter
if(count==) // IF count = 0 then all the character are matched that is first half is a mirror image of second half.
System.out.println("It is a Palindrome");
System.out.println("Not a palindrome");
Incoming terms: check whether a number is a palindrome number or not.