How to check whether a String is a Palindrome or not in java?

A string is said to be palindrome if it reads the same backward as forward. In other words, if the reverse of a string equals the same string can also be called a Palindrome string. For example, madam is a Palindrome string.

Here we will show you two solutions to check whether a string is a palindrome or not. Let’s see one by one below:

Solution #1 : Using String Reverse

PalindromeString1.java

package com.javacodepoint.programs;

public class PalindromeString1 {

	// Main method
	public static void main(String[] args) {

		//initializing a string to check string palindrome 
		String str = "madam";
		
		//check palindrome
		if(isPalindromeString(str)) {
			System.out.println(str+" is a palindrome string.");
		}else {
			System.out.println(str+" is not a palindrome string.");
		}
	}
	
	// Palindrome checking method
	public static boolean isPalindromeString(String str) {
		String reverse="";
		
		for(int i=0;i<str.length();i++) {
			reverse = str.charAt(i) + reverse;
		}
		
		// checking whether both are equals
		if(reverse.equals(str)) {			
			//String is Palindrome
			return true;			
		}else {			
			//String is not Palindrome
			return false;
		}
	}

}

OUTPUT:

madam is a palindrome string.

Solution #2 : Without String Reverse

PalindromeString2.java

package com.javacodepoint.programs;

public class PalindromeString2 {

	// Main method
	public static void main(String[] args) {

		// initializing a string to check string palindrome
		String str = "madam";

		// check palindrome
		if (isPalindromeString(str)) {
			System.out.println(str + " is a palindrome string.");
		} else {
			System.out.println(str + " is not a palindrome string.");
		}
	}

	// Palindrome checking method
	public static boolean isPalindromeString(String str) {

		boolean isPalindrome = true;

		// iterating the string upto the half of the string length
		for (int i = 0; i < str.length() / 2; i++) {

			if (str.charAt(i) == str.charAt(str.length() - 1 - i)) {
				continue;
			} else {
				isPalindrome = false;
				break;
			}
		}

		//returning the result
		return isPalindrome;
	}

}

OUTPUT:

madam is a palindrome string.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *