How to Check Palindrome String in Java?

Method - 1: Native

import java.io.*;

class Palindrom 
{
    public static boolean checkPalindrome(String str)
    {
        // To store the reverse of string
        String revStr = "";

		boolean isPalindrom = false;

		for (int i = str.length() - 1; i >= 0; i--) 
		{
			revStr = revStr + str.charAt(i);
		}

		// Checking if string and reverse of string are equal
		if (str.equals(revStr)) 
		{
			isPalindrom = true;
		}
		// return true if string are plaindrom otherwise false
		return isPalindrom;
	}
	
	public static void main(String[] args)
	{
		String str1 = "sir";
		String str2 = "madam";

		System.out.println(str1 + " is palindrom: " +checkPalindrome(str1));
		System.out.println(str2 + " is palindrom: " +checkPalindrome(str2));
	}
}

Output

sir is palindrom: false
madam is palindrom: true

Time Complexity: O(n)

Space Complexity: O(n)

Method - 2: Recursive

import java.io.*;

class GFG 
{
	public static boolean checkPalindrome(int i, int j, String A)
	{
		// comparing the two pointers
		if (i >= j) {
			return true;
		}

		// comparing the characters on those pointers
		if (A.charAt(i) != A.charAt(j)) {
			return false;
		}

		// checking everything again recursively
		return checkPalindrome(i + 1, j - 1, A);
	}

	public static boolean checkPalindrome(String A)
	{
		return checkPalindrome(0, A.length() - 1, A);
	}

	// main function
	public static void main(String[] args)
	{
	    String str1 = "sir";
        String str2 = "madam";
        
		System.out.println(str1 + " is palindrom: " +checkPalindrome(str1.toLowerCase()));
		System.out.println(str2 + " is palindrom: " +checkPalindrome(str2.toLowerCase()));
	}
}

Output

sir is palindrom: false
madam is palindrom: true

Time Complexity: O(n)

Space Complexity: O(n)

Method - 3: Two - Pointer

public class Palindrom 
{
	static boolean checkPalindrome(String str)
	{
		int i = 0, j = str.length() - 1;

		while (i < j) {

			// If there mismatch
			if (str.charAt(i) != str.charAt(j))
				return false;
				
			i++;
			j--;
		}
		
		return true;
	}

	public static void main(String[] args)
	{
		String str1 = "sir";
        String str2 = "madam";
		
		System.out.println(str1 + " is palindrom: " +checkPalindrome(str1.toLowerCase()));
		System.out.println(str2 + " is palindrom: " +checkPalindrome(str2.toLowerCase()));
	}
}

Output

sir is palindrom: false
madam is palindrom: true

Time Complexity: O(n)

Space Complexity: O(1)

teststep banner