Tutorials Hut

Java Program For Palindrome Problem

In this article we will look into the java program for the palindrome problem. Let’s understand what a palindrome is – A palindrome is a string or word which will read the same if we read from left to right or right to left.

Example 1:

abba (this string is a palindrome which will read abba if we read from left to right or right to left)

Example 2: zxkc

(this string is NOT a palindrome as does not read same from both ends)

Java Program For Palindrome Problem

Below example we have provided two solutions to find if a string is palindrome or not.

package problems;

class PalindromeProblem {
static boolean isPalindromeSol1(String str)
{
     //start and end index of string
     int i = 0;
     int j = str.length() - 1;

     while (i < j) {
         // Check if no match return false
         if (str.charAt(i) != str.charAt(j))
             return false;
         // Increment index
         // decrement index
         i++;
         j--;
     }
     // if all chars match from both ends then it is a palindrome
     return true;
}

static boolean isPalindromeSol2(String str)
{
     StringBuilder strBuilder = new StringBuilder(str);
     //using string builder method to reverse the data
     return str.equals(strBuilder.reverse().toString());
}

public static void main(String[] args)
{
     System.out.println("Solu 1, String 'abba' is palindrome "+ isPalindromeSol1("abba"));
     System.out.println("Solu 1, String 'abda' is palindrome "+ isPalindromeSol1("abda"));
     System.out.println("Solu 2, String 'abba' is palindrome "+ isPalindromeSol2("abba"));
     System.out.println("Solu 2, String 'abda' is palindrome "+ isPalindromeSol2("abda"));
}
}

Output

Solu 1, String ‘abba’ is palindrome true

Solu 1, String ‘abda’ is palindrome false

Solu 2, String ‘abba’ is palindrome true

Solu 2, String ‘abda’ is palindrome false