Palindrome program in Java with Examples & Programs

Palindrome: Palindrome is a Word, number (or) sequence of characters are the same after the reverse of the word (or) number.

Example of Palindrome:


Number Palindrome Examples: 6556, 343, 1441, 24542,757.

String Palindrome Examples: level, madam, refer, rotor, lol.

Example of number Palindrome:

class Palindrome1
 public static void main(String args[])
 { 
 int i,sum=0,temp;   
 int n=757;
 temp=n;   
 while(n>0)
 {   
  i=n%10;   
  sum=(sum*10)+i;   
  n=n/10;   
  }   
  if(temp == sum)   
   System.out.println(sum + " is a palindrome number ");  
  else
   System.out.println(sum + "is not palindrome");  
}
}

Output :
757 is a palindrome number.

See also: Switch statement in Java

To check Palindrome or not for user-entered number:


import java.util.Scanner;
class Palindrome2
 public static void main(String args[])
 { 
 int i,sum=0,temp;  
 Scanner s = new Scanner(System.in);
 System.out.print("Enter the value of N = ");
 int n = s.nextInt();
 temp = n;   
 while(n>0)
 {   
  i=n%10;   
  sum=(sum*10)+i;   
  n=n/10;   
  }   
  if(temp == sum)   
   System.out.println(sum + " is palindrome number ");  
  else
   System.out.println(sum + "is not palindrome");  
}
}

Example of String Palindrome:

import java.util.Scanner;
class Palindrome
{
 public static void main(String[] args)
 {
  String original,reverse = "";
  Scanner in = new Scanner(System.in);
  System.out.println("Enter the Text");
  original = in.nextLine();
  int length = original.length();
  for(int i = length - 1;i >= 0; i--)
  {
  reverse = reverse + original.charAt(i);
  }
  if(original.equals(reverse))
  System.out.println(reverse + " is a Palindrome");
  else
  System.out.println(reverse + " is Not a Palindrome");
  }
}

Output:

Enter the Text
madam
madam is a Palindrome

Share:

Ads

Search This Blog

  • ()
Powered by Blogger.

Strings in C With Syntax, C String Program with output

Strings in C :  Strings can be defined as the one-dimensional array of characters terminated by a null ('\0'). The difference betwee...