ads

Saturday, February 13, 2016

Java program to check palindrome

Java palindrome program: Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome. Some other palindrome strings are "mom", "madam", "abcba".

Java programming source code

import java.util.*;
 
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
 
System.out.println("Enter a string to check if it is a palindrome");
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("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
 
}
}
Download Palindrome program class file.
Output of program:
palindrome
Another method to check palindrome:
import java.util.*;
 
class Palindrome
{
public static void main(String args[])
{
String inputString;
Scanner in = new Scanner(System.in);
 
System.out.println("Input a string");
inputString = in.nextLine();
 
int length = inputString.length();
int i, begin, end, middle;
 
begin = 0;
end = length - 1;
middle = (begin + end)/2;
 
for (i = begin; i <= middle; i++) {
if (inputString.charAt(begin) == inputString.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Palindrome");
}
else {
System.out.println("Not a palindrome");
}
}
}
Both the above codes consider string as case sensitive, you can modify them so that they ignore the case of string. You can either convert both strings to lower or upper case for this. But do not modify original strings as they may be further required in program.

No comments:

Post a Comment