Java program to Check if a String is Palindrome

In Java, to check whether a string is palindrome or not we can create a custom method to do string reversal (As custom method is more efficient and reusable) along with that we can also use two-pointer approach or String reversal approach.

A String is known as palindrome String, If the reversed string is equal to the original string.

For Example: “civic” is palindrome string as its reversal is same as “civic” and “Expert” is not a palindrome string as reverse of it is “trepxE” which is not same as “Expert”.

In this article we will learn writing a String is Palindrome or not through examples, detailed logic and program explanation for better understanding.

Required Knowledge

  • Java programming basics
  • Java operators
  • Loop concepts
  • Conditional statements

Problem Statement

We have to write a Java program to check whether a string is palindrome or not. This program should ask the user to give a string as an input. And then it will check if the string remains the same or not after reversal. If the reversed string is identical to the original input string, the program should print “String is Palindrome”. Otherwise, it should print “String is not a palindrome”. Our Program should perform this task. Let’s see an example,

Example:

For a given input String str “Madam”, Output should be “Palindrome”.

Explanation:

Input String str: "Madam"

Reverse of the String revStr : madaM

The last character is "M", which raises an issue with case sensitivity and indicates that the text is "Not a palindrome".

but for Input String str: "madam", (Here, we are ignoring case sensitivity, so we consider "M" in lowercase),

If we reverse the string, it will be "madam".

So here we can say that "madam" is a palindrome.

Logic to Check a String is Palindrome or not

There are multiple logics to check a string is palindrome or not in the java programing language.

Logic 1: String Reversal approach

  • We can implement the program by first reversing the input string using reverse iteration.
  • Reverse iteration: Use a for loop that starts from the end of the input string and iterates backward towards the beginning.
  • Inside the loop, add each character to a new string (outputString) to store the reversed string.
  • Then, using an if-else condition, we’ll compare the reversed string with the input string to check for equality using the equalsIgnoreCase() method.
  • If the reversed string matches the input string, it indicates that the text is a palindrome. Otherwise, if they are not equal, the text is not a palindrome.

Logic 2: Custom method

  • As we need to check if a given string is a palindrome or not, we can create a custom method to reverse the string that takes the input string.
  • Inside the custom method, we will perform string reversal using reverse iteration.
  • After reversing, we will store the result in the variable revString and compare it to the original input string using an if-else condition with the equalsIgnoreCase() method.
  • If the equalsIgnoreCase() method returns true, our program will print “String is Palindrome”; otherwise, it will print “String is not Palindrome.”

Logic 3: two pointer approach

  • In two pointer approach: Initialize a string variable with the input string given by the user.
  • Take two pointers of type int, i and j, and initialize them to the start (0) and end (string.length()-1) of the string, respectively.
  • Initialize a boolean variable isPalindrome to true.
  • Iterate through the input string using a while loop:
    • If the character at index i is not equal to the character at index j, set isPalindrome to false and break the loop.
    • If a match is found (i.e., the characters at i and j are the same), increment i by 1 and decrement j by 1.
  • This iteration continues until i becomes greater than or equal to j.
  • If isPalindrome is still true after exiting the loop, print “Input String is a palindrome”. Otherwise, print “String is not a palindrome”.

Java program to Check whether a String is Palindrome or not

Program 1: String Reversal approach

In the below program we are using String reversal approach to check whether a string is palindrome or not.

import java.util.Scanner;
public class Palindrome2 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the text:");
		String str = s.nextLine();
		String outputString="";
		for (int j = str.length() - 1; j >= 0; j--) {
			outputString += str.charAt(j);
			}
		if(outputString.equalsIgnoreCase(str)) {
			System.out.println(str+" : "+ "Palindrome");
		}
		else {
			System.out.println(str+" : "+"not a palindrome");
		}
		s.close();
	}
}

Output:

Enter the text:
Animal
Animal : not a palindrome

Java program explanation to check whether a string is palindrome

  1. The program ask the user to enter a text.
  2. It reads the input text using a Scanner.
  3. The program then iterates over the characters of the input string(str) in reverse order and create a new string outputString by appending each character.
  4. It checks if outputString is equal to the original input string (str), ignoring case. If the two strings are equal (indicating that the input string is a palindrome), it prints “Palindrome” along with the original string.
  5. Otherwise, if the two strings are not equal, it prints “not a palindrome” along with the original string.
  6. Finally, the Scanner is closed to release system resources.

Program 2: Custom method

In the below program we are creating a custom method to check whether a string is palindrome.

import java.util.Scanner;
public class Palindrome {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the text:");
		String string = s.nextLine();
		String outputString="";
	if(getReverse(string).equalsIgnoreCase(string))
		outputString=string+ " it is palindrome";
	else
		outputString= string +" not a palindrome";
		System.out.println(outputString);
		s.close();
	}
	public static String getReverse(String inputString) {
		String revString="";
		for (int j = inputString.length() - 1; j >= 0; j--) {
			revString += inputString.charAt(j);
			}
		return revString;
	}
}

Output:

Enter the text:
Civic
Civic it is palindrome

Java program explanation to check whether a string is palindrome

  1. The program reads a string input from the user using the Scanner class.
  2. The main method calls the getReverse method to reverse the input string.
  3. The getReverse method iterates through the input string from the end to the beginning and constructs the reversed string.
  4. The main method compares the reversed string with the original string using equalsIgnoreCase to ignore case differences.
  5. If the reversed string is equal to the original string, the program prints that the input string is a palindrome.
  6. If the reversed string is not equal to the original string, the program prints that the input string is not a palindrome.
  7. Finally, the Scanner is closed to free up resources.

Program 3: two-pointer approach

In the below program we are using two-pointer approach to check whether a string is palindrome.

import java.util.Scanner;
public class Palindrome1 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter a string");
		String string =s.nextLine();
		int i=0, j=string.length()-1;
		boolean isPalindrome =true;
		while(i<j) {
			if(string.charAt(i)!=string.charAt(j)) {
				isPalindrome=false;
				break;
			}
			i++;
			j--;
		}
		if(isPalindrome) {
			System.out.println(string + ":" + "is palindrome");
		}
		else {
			System.out.println(string+ " :"+ "is not a palindrome");
		}
		s.close();
	}
}

Output:

Enter a string
madam
madam:is palindrome

Java program explanation to check whether a string is palindrome

  1. The java program asks the user to enter a string.
  2. It reads the input string using a Scanner object.
  3. Two pointers i and j are initialized, pointing to the beginning and end of the string respectively.
  4. A boolean variable isPalindrome is initialized to true.
  5. Using a while loop, characters at positions i and j are compared.
  6. If the characters are not equal, isPalindrome is set to false, and the loop is exited.
  7. The pointers i and j are moved inward towards the center of the string.
  8. After the loop, if isPalindrome is still true, the program prints that the string is a palindrome.
  9. If isPalindrome is false, the program prints that the string is not a palindrome.
  10. Finally, the Scanner object is closed.

Conclusion

In this article, we have learnt how to check if a string is palindrome or not in Java. We have seen the logic and implemented the program using string reversal approach, by creating a custom method and using two pointer approach in Java. Hope this article helped you in the understanding of the program.

You can also check our another awesome tutorials

Happy Java Programming!!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.