Palindrome Program In Java With Examples

Palindrome Program

What is a Palindrome?

A palindrome is a Number/String that is the same after reverse.

Example 1: 5445,6556,455554.

Example 2: mom, repaper, tenet.

Write a program to check the given string palindrome or not?

Solution 1: By using StringBuffer.


public class  PalindromeSolution1{

	public static void isPalindrome(String paliString) {

		/* Here we are reversing string by using StringBuffer API and setting in to
		 another string.*/
		String reversepaliString = new StringBuffer(paliString).reverse().toString();

		/*
		 * Here we are checking both strings equals or not if it's equals
		 *  given string is a Palindrome or else not a Palindrome.
		 * */
		if (paliString.equals(reversepaliString)) {
			
			System.out.println(paliString + " is Palindrome");
			
		} else {
			
			System.out.println(paliString + " is not Palindrome");
			
		}
	}

	public static void main(String[] args){
		
		isPalindrome("mom");
		isPalindrome("repaper");
		isPalindrome("clarifyall");
		
	}
	

}

Output :

mom is Palindrome
repaper is Palindrome
clarifyall is not Palindrome

Solution 2: By using for loop.

public class  PalindromeSolution2{

	public static void isPalindrome(String paliString) {
		
		String reverseString = "";
		
		/*
		 * Here we are reversing given string and setting in to anther string
		 * */
		for (int i=paliString.length()-1;i>=0;i--) {
			
			reverseString = reverseString + paliString.charAt(i);
			
		}
		
		/*
		 * Here we are checked given string and reversed string same or not 
		 * if same given string is palindrome else given string not palondrome.
		 */
		if (paliString.equalsIgnoreCase(reverseString)) {

			   System.out.println(paliString+" is palindrome.");

		} else {

			   System.out.println(paliString+" is not palindrome.");

		}
		
		
	}

	public static void main(String[] args){
		
		isPalindrome("tenet");
		isPalindrome("repaper");
		isPalindrome("java");
		
   }

}

Output:

tenet is palindrome.
repaper is palindrome.
java is not palindrome.

Manohar Kota

About Manohar

I, Manohar am the founder and chief editor of ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply