Write a Program to Check Given String is a Palindrome or Not


This Java program checks whether an input string is a palindrome or not. A palindrome string is a string that remains the same when its characters are reversed.

  • The program starts by using a Scanner object to read in a string from the user. It then initializes a variable rev as an empty string and a variable len to store the length of the input string.
  • The program then uses a for loop to reverse the input string by iterating through the characters of the string from the end to the beginning, and concatenating each character to rev.
  • Finally, the program checks whether the original input string is equal to the reversed string when both strings are converted to lowercase. If they are equal, then the program prints that the input string is a palindrome. Otherwise, it prints that the input string is not a palindrome.

Overall, this program correctly checks whether an input string is a palindrome or not. However, it could be improved by handling the case where the input string contains spaces or other special characters. In its current form, the program does not remove any spaces or special characters from the input string before checking for palindrome-ness.

Source Code

import java.util.Scanner;
class Palindrome_String
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The String :");
		String str = input.nextLine();
		String rev = "";
		int len = str.length();
		for (int i = (len - 1); i >=0; --i)
		{
			rev = rev + str.charAt(i);
		}
		if (str.toLowerCase().equals(rev.toLowerCase()))
		{
			System.out.println(str + " is a Palindrome String.");
		}
		else
		{
			System.out.println(str + " is not a Palindrome String.");
		}
	}
}

Output

Enter The String :madam
madam is a Palindrome String

Example Programs