Palindrome String in Java

By: Grant Braught Emailed: 1767 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Checking if a String is a Palindrome is a common assignment given to Java students. This sample class is a helpful class that checks for various scenarios to find out if the given string is a palindrome.
public class Palindrome {
    private String pal;
    
    public Palindrome(String initPal) {
	pal = initPal.toUpperCase();
    }
    
    public boolean isPalindrome() {
       
	if (pal.length() <= 1) {
	    // String has only one character so it
	    // is a Palindrome by definition.
	    return true;		// BASE CASE.
	}
	
	// Get the first and last characters of the String.
	char first = pal.charAt(0);
	char last = pal.charAt(pal.length()-1);
	
	if (Character.isLetter(first) &&
	    Character.isLetter(last)) {
	    // The first and last characters are both letters..

	    if (first != last) {
		// The first and last letters are different
		// so the string is not a Palindrome.
		return false;           // BASE CASE.
	    }
	    else {
		// The first and last characters are both letters,
		// and they are both the same. So, the string is 
		// a palindrome if the substring created by dropping
		// the first and last characters is a palindrome.
		Palindrome sub = new Palindrome(
			         pal.substring(1,pal.length()-1));
		return sub.isPalindrome();  // RECURSIVE CASE.
	    }
	}
	else if (!Character.isLetter(first)) {
	    // The first character in the string is not a letter.
	    // So the string is a palindrome if the substring created
	    // by dropping the first character is a palindrome.
	    Palindrome sub = new Palindrome(pal.substring(1));
	    return sub.isPalindrome();      // RECURSIVE CASE.
	}
	else {
	    // The last character in the string is not a letter.
	    // So the string is a palindrome if the substring created
	    // by dropping the last character is a palindrome.
	    Palindrome sub = new Palindrome(
                             pal.substring(0,pal.length()-1));
	    return sub.isPalindrome();      // RECURSIVE CASE.
	}
    }

    public static void main(String[] args) {
	Palindrome p1 = new Palindrome("Madam, I'm Adam.");
	System.out.println(p1.isPalindrome());
	Palindrome p2 = new Palindrome("Nope!");
	System.out.println(p2.isPalindrome());
	Palindrome p3 = new Palindrome("dad");
	System.out.println(p3.isPalindrome());
	Palindrome p4 = new Palindrome("Go hang a salami, I'm a lasagna hog.");
	System.out.println(p4.isPalindrome());
    }
}


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(9)


1. View Comment

the discussion is not enogh

View Tutorial          By: gulstan at 2011-03-27 03:47:24
2. View Comment

The one more best way is

public class Palindrome {
static public String pal(String str, int i, int j){
if(str.length()/2 != i)
if(str.charAt(i)==str.charAt(j))
pal(str,++i,--j);
else
return "String is Not palaindrome";

return "String is palaindrome";
}
public static void main(String[] args) {
String str = args[0];
System.out.println(pal(str,0,str.length()-1));
}
}


View Tutorial          By: Palla Subramanyam at 2012-01-25 20:18:03
3. View Comment

This should save some time

class palindrome
{
public static void main(String[] args)
{
System.out.println("\n"+"enter the value");
String abc=args[0];
String def=new StringBuffer(abc).reverse().toString();
System.out.println(def);
System.out.println(abc);
if(abc.equals(def))
System.out.println("yes its not a palindrome");
else
System.out.println("No, it is a palindrome");

}
}


View Tutorial          By: vamsi gude at 2012-03-20 18:27:24
4. View Comment

The smiple easy and best way is :)
------------------------------------------------
import java.util.Scanner;
public class Palindrome {
static String str2 = "";
static String comString;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String enteredString = s.next();
comString = enteredString;
int stringLength = enteredString.length();
for (int i = stringLength - 1; i >= 0; i--) {
char currentChar = enteredString.charAt(i);
String str1 = Character.toString(currentChar);
str2 = str2.concat(str1);
}
if (str2.equals(comString)) {
System.out.println("Is Pallandrome");
} else {
System.out.println("Not a Pallandrome");
}
}
}


View Tutorial          By: Sandhya at 2012-06-21 06:08:25
5. View Comment

@Palla Subramanyam : Your logic is correct, but SOP is not proper.

if(abc.equals(def))
System.out.println("yes its a palindrome");
else
System.out.println("No, it is not a palindrome");


View Tutorial          By: Roopesh H at 2012-07-27 04:47:48
6. View Comment

Why use recursion in Java, even for Strings? The stack will grow and use more time and space. If we used Scheme, ML or a language with iterative recursion (tail recursion) it might be our only choice, but not in Java. Why not just use a loop?

Something like:
boolean isPalindrome(String str){
int i = 0;
int j = str.length() - 1;
while(i < j){
if(str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}

And maybe add a couple of tests ala:
if(!Character.isLetter(str.charAt(i)))
i++
if(!Character.isLetter(str.charAt(j)))
j--
or just
str.replaceAll("[^\w]", "");


View Tutorial          By: Kristoffer L at 2012-11-21 01:51:36
7. View Comment

simple way friends:
public class palindrome {
public static void main(String[] args) {
String s="malayalam";
int count=0;
int gee=0;
for(int i=0;i<s.length()/2;i++)
{
char[] f=s.toCharArray();
if(f[i]==f[s.length()-1-i])
{
count++;
}
else
{
gee++;
}
}
if(gee>0)
{
System.out.println("not palindrome");
}
else
{
System.out.println("palindromr");}
}

}


View Tutorial          By: Manoj at 2013-01-07 02:18:00
8. View Comment

this works
------------------------------------------

import java.util.Scanner;

public class PalindromeString {
static String str2 = "";
static String comString;
public static void main(String[] args) {
System.out.println("\n"+"enter the value");
Scanner s = new Scanner(System.in);
String enteredString = s.next();
comString = enteredString;
int stringLength = enteredString.length();
for (int i = stringLength - 1; i >= 0; i--) {
char currentChar = enteredString.charAt(i);
String str1 = Character.toString(currentChar);
str2 = str2.concat(str1);
}
if (str2.equals(comString)) {
System.out.println("Is Pallandrome");
} else {
System.out.println("Not a Pallandrome");
}
}
}


View Tutorial          By: Aeron at 2013-10-20 04:50:51
9. View Comment

import java.util.*;

class Pstring
{
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.");

}
}


View Tutorial          By: Bhaskar.pg at 2014-05-29 12:39:52

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Grant Braught
Sum of 1 to N in C++
Vector variables in C++
Reverse a String in C++
Pass by Reference vs Pass Value in C++ functions
Pass by Reference in C++ functions
Checking Prime Number in C++
Insert, Delete, Search, Print an int Array in Java
Insert, Delete, Search, Print an int Array in Java
Palindrome String in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
Sample Java program shows how to write to COM port using Java.
Vector example in Java
Java File
Palindrome String in Java
Simple java program to add an element to specified index of Java ArrayList
Java program for Map
How to reverse the elements in a Single dimension array and display the output
Fields in JasperReports
Disadvantages of using Native methods in Java
instanceof sample program in Java
Transient vs Volatile modifiers in Java
how to use boolean data type in Java
char data type in Java
How to use ArrayList in Java
ThreadGroup Sample in Java
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet