Hello Folks,

In last post we have seen java program to check if any given string is palindrome or not without using any method. In this post we will write java program to check if any given string is palindrome or not with help of reverse method.

WHAT IS PALINDROME STRING?

A palindromic string is a string that remains the same when its characters are reversed.

For Example: NAAN, AMMA  etc.

Java Program:

 


package JavaPrograms;

import java.util.Scanner;

public class PalindromeCharStringUsingStringBuffer 
{
public static void main(String[] args) {
	
	// Taking input from user
	Scanner sc= new Scanner(System.in);
	System.out.println("Please enter the string to know palindrome:");
	String inputByUser= sc.nextLine();
	//Converting String in to StringBuilder
	StringBuilder strOriginal= new StringBuilder(inputByUser);
	// reversing string
	StringBuilder strReverse= new StringBuilder(strOriginal).reverse();
	//since stringBuildr/Buffer do not override equals method so it will not check content
	//To verify content we can use valueOf method of String class. This method class toString() internally.
	if(String.valueOf(strOriginal).equals(String.valueOf(strReverse)))
		System.out.println("Result:Palindrome");
	else
	    System.out.println("Result:Not Palindrome");
	//Another way to verify content  using toString()
	 if((strOriginal.toString()).equals(strReverse.toString()))
		System.out.println("Result:Palindrome");
	 else
		System.out.println("Result:Not Palindrome");
	 //Using compareTo method
	 if((strOriginal.toString()).compareTo(strReverse.toString())==0)
		System.out.println("Result:Palindrome");
	 else
		System.out.println("Result:Not Palindrome");
		 
		    
}
}

Output:
Please enter the string to know palindrome:
AMMA
Result:Palindrome
Result:Palindrome
Result:Palindrome

Please enter the string to know palindrome:
NANA
Result:Not Palindrome
Result:Not Palindrome
Result:Not Palindrome

Please enter the string to know palindrome:
AMMA AMMA
Result:Palindrome
Result:Palindrome
Result:Palindrome

 

You can run above program for multiple inputs and if it fails for any condition, let me know.

#HappyCoding

Leave a Reply