Written by Sai Sandeep Thota on February 23, 2014 in Java > Programming

Java Program to check if String is Palindrome or not using Command Line Input

GET ALERTS:

Get our Latest updates delivered to your mailbox!

We have already written Java Program to check String is Palindrome or Not, now in this article we are going to describe Java Program to check if a String is Palindrome or not using Command Line Input. This program also checks whether a sentence is a Palindrome or not.

When a string or sentence is given, we need to check whether the given input is a Palindrome or not. The process is discussed below:

#1. Java command line input is stored in the form of array (String args[]). As it will be a complicated task to perform Palindrome check on an Array, we are converting the Array to String using the toString() method available in the util package. We are using replaceAll() method in order to remove the array braces “[ ]” and storing it in the String variable msg.
#2. Again we are using replaceAll() method and using a simple regex expression [^A-Za-z] so that to match all strings that contain a non-letter and replace them and toLowerCase() method is used to convert the string to Lowercase.
For example: If the given Palindrome String is: Race Car, if we reverse it, the Output will be: raC ecaR. In order to ignore the spaces or commas, full stop etc., we are using the Regex expression and we are converting the string to lowercase so the the output will be : racecar (Palindrome String).
#3. Then we are constructing a string using the StringBuilder and reversing the String using the reverse() method and storing it in the String variable called rev.
#4. Finally we are using equals method to check value in the msg variable is equal to rev variable, if equal then it is a Palindrome else it is not a Palindrome.

Download Source Code

Java Program to check if String is Palindrome or not using Command Line Input

import java.util.Arrays;

class palindrome {
		public static void main(String args[]) {
			String msg = Arrays.toString(args).replaceAll("\\[","").replaceAll("\\]","");
			msg = msg.replaceAll("[^A-Za-z]", "").toLowerCase();
			String rev = new StringBuilder(msg).reverse().toString();
			if(msg.equals(rev))	{
				System.out.println("Given String "+msg+" is a Palindrome.");
			}
			else
			{
				System.out.println("Given String "+msg+" is not a Palindrome.");
			}
		}
}

Output:
Java Program to check if String is Palindrome or not using Command Line Input

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: