Hello Folks,

In last post we have seen java program to check if any given number is palindrome or not. In this post we will write java program to check if any given string is palindrome or not.

WHAT IS PALINDROME STRING?

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

For Example: NAAN, AMMA AMMA etc.

Logic:

  1. We will convert given string in to char array first.
  2. Read char from char array from last index and concatenate.

Java Program:


package JavaPrograms;

import java.util.Scanner;

public class PalindromeCharString 
{
public static void main(String[] args) {
	
	// Reading string from user input
	Scanner sc= new Scanner(System.in);
	System.out.println("Please enter the string to check palindrome:");
	String inputByUser= sc.nextLine();
	//converting string in to char array
	char[] stringInChar= inputByUser.toCharArray();
	String reverseInput="";
	// reading char by char and forming a string
	for(int i=stringInChar.length-1;i>= 0;i--)
	{
		reverseInput= reverseInput+stringInChar[i];
	}
	System.out.println("Inout string:"+inputByUser);
	System.out.println("Reverse String:"+reverseInput);
	if(inputByUser.equals(reverseInput))
		System.out.println("Entered string is palindrome.");
	else
		System.out.println("Entered string is not palindrome.");
}
}

Output:
Please enter the string to check palindrome:
NANA
Inout string:NANA
Reverse String:ANAN
Entered string is not palindrome.

Please enter the string to check palindrome:
AMMA
Inout string:AMMA
Reverse String:AMMA
Entered string is palindrome.

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

#HappyCoding

 

One thought on “Java Program to check if any string is palindrome. (Without using reverse method)

Leave a Reply