Thursday , September 21 2017
Home / Blue J / Java program to check for palindrome

Java program to check for palindrome

Java program to check for Palindrome.

What is a palindrome number or palindrome string? There are following definitions:

  1. A palindrome number or a palindrome string is one whose mirror image is same as itself.
  2. A Palindrome is exactly same as seen from beginning or ending.

Concept used here:

if(s.charAt(i) == s.charAt(l-i-1);

MADAM :

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.

import java.util.*;
class palindrome
{
	public static void main(String args[])
	{
	String s;
	int l,i=0,count=0;
	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
	i++;
	}
	if(count==0)	// 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");
	else
	System.out.println("Not a palindrome");
	}
}

OUTPUT:

Java program for palindrome
Java program to check for palindrome

Incoming terms: check whether a number is a palindrome number or not.

Check Also

Program to check Upper Triangular matrix

What is Upper Triangular Matrix?  An upper triangular matrix is a square matrix in which ...

Leave a Reply

Your email address will not be published. Required fields are marked *