Java Program to check String is Palindrome Or Not (Best way and Recursive)

1. Introduction


In this article, We will be learning how to write a java program to check whether a given string is a palindrome or not. This can be solved in many ways and will see all possible ways.

First, What is a palindrome? A String is said palindrome if and only if all characters of the string remain the same even the string is reversed. To solve this first we need to reverse the string and compare the reversed string with the original string. If both are same then the given string is a palindrome, Otherwise, it is not.

java-program-check-string-palindrome


Example:

String input = "madam";
String reversedString = "madam";

Let us observe that input and reversedString contents are the same. So, the input string is called a palindrome.


String input2 = "hello";
String reversedString2 = "olleh";

input2 and reversedString2 contents are not the same so input2 "hello" is not a palindrome.

In previous tutorials, we have shown the java program to find all palindromes for a given range. Read more here.

As we stated earlier this can be solved by using java built-in API methods or use the core logic to check or determine string is a palindrome.

.
A) Using built-in reverse() method
B) Using StringBuffer class
C) Using additional String
D) Without using any library method or additional Strings.
F) Recursive approach
.

2) String Palindrome Program: Using the built-in reverse() method of StringBuffer


StringBuffer API has a reverse() method which does the job for us to reverse the contents. reverse() method returns the StringBuffer so we need to convert it to String by invoking the toString() method. toString() is to convert the StringBuffer to String.

package com.javaprogramto.engineering.programs;

public class StringPalindromeReverse {

public static void main(String[] args) {
String input1 = "madam";
String reversedString1 = reverseString(input1);

if (input1.equals(reversedString1)) {
System.out.println(input1 + " is a palindrome");
} else {
System.out.println(input1 + " is not a palindrome");
}

String input2 = "hello";
String reversedString2 = reverseString(input2);

if (input2.equals(reversedString2)) {
System.out.println(input2 + " is a palindrome");
} else {
System.out.println(input2 + " is not a palindrome");
}

}

private static String reverseString(String input) {

StringBuffer buffer = new StringBuffer();
buffer.append(input);

return buffer.reverse().toString();
}

}

Output:

madam is a palindrome
hello is not a palindrome

3) String Palindrome Program: Using StringBuffer class append() method


We run the for loop from index length-1 to 0. That means retrieving each character from the last index to the first index and then add it to StringBuffer. After adding all characters of string to StringBuffer Finally covert StringBuffer to String using toString() method.

Read more on for loop.

package com.javaprogramto.engineering.programs;

public class StringPalindromeAppend {

public static void main(String[] args) {
String input1 = "civic";
String reversedString1 = reverseString(input1);

if (input1.equals(reversedString1)) {
System.out.println(input1 + " is a palindrome");
} else {
System.out.println(input1 + " is not a palindrome");
}

String input2 = "civics";
String reversedString2 = reverseString(input2);

if (input2.equals(reversedString2)) {
System.out.println(input2 + " is a palindrome");
} else {
System.out.println(input2 + " is not a palindrome");
}

}

private static String reverseString(String input) {

StringBuffer buffer = new StringBuffer();

for (int i = input.length() - 1; i >= 0; i--) {
buffer.append(input.charAt(i));
}
return buffer.toString();
}

}

Output:

civic is a palindrome
civics is not a palindrome

4. String Palindrome Program: Using a new String variable


As in the above, we use String instead of StringBuffer and add all characters to a new String object. See the below program.

package com.javaprogramto.engineering.programs;

public class StringPalindromeAdditionalString {

public static void main(String[] args) {
String input1 = "radar";
String reversedString1 = reverseString(input1);
if (input1.equals(reversedString1)) {
System.out.println(input1 + " is a palindrome");
} else {
System.out.println(input1 + " is not a palindrome");
}

String input2 = "radars";
String reversedString2 = reverseString(input2);

if (input2.equals(reversedString2)) {
System.out.println(input2 + " is a palindrome");
} else {
System.out.println(input2 + " is not a palindrome");
}

}

private static String reverseString(String input) {

String output = "";

for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
return output;
}

}

Output:

radar is a palindrome
radar1 is not a palindrome

In the above three approaches, the problem is consuming the additional memory using StringBuffer or additional String instance.

5. String Palindrome Program: Recursive approach


Here logic to compare the first index value and last index value and then next first index -1 and last index -1.. like this compare till the start index becomes a mid-index. If anyone of these comparison fails then it is not a palindrome. If all comparisons are equal then it is a palindrome.

You need to observe that not used any additional memory and no library methods apart from charAt(). This solution is quite precise and used logic. This the answer that the interviewer expects if you are an experienced developer.

package com.javaprogramto.engineering.programs;

public class StringPalindromeWithoutLibraryHelp {

public static void main(String[] args) {
String input1 = "level";
boolean isPal1 = isPalindrome(input1);
if (isPal1) {
System.out.println(input1 + " is a palindrome");
} else {
System.out.println(input1 + " is not a palindrome");
}

String input2 = "levels";
boolean isPal2 = isPalindrome(input2);

if (isPal2) {
System.out.println(input2 + " is a palindrome");
} else {
System.out.println(input2 + " is not a palindrome");
}

}

private static boolean isPalindrome(String input) {

int length = input.length();
for (int start = 0, end = length - 1; start <= length / 2; start++, end--) {

if (input.charAt(start) != input.charAt(end)) {
return false;
}
}
return true;
}

}

Output:

level is a palindrome
levels is not a palindrome

6. String Palindrome Program: Recursive approach


The below-shown program is implemented using a recursive approach. Read the comments in isPalindrome() method will give a clear understanding of each line of code.
Comparatively, this way uses two methods charAt() and substring() methods.

Recursive program to print the Fibonacci series and find the nth Fibonacci number.


package com.javaprogramto.engineering.programs;

public class StringPalindromeRecursive {

public static void main(String[] args) {
String input1 = "racecar";
boolean isPal1 = isPalindrome(input1);
if (isPal1) {
System.out.println(input1 + " is a palindrome");
} else {
System.out.println(input1 + " is not a palindrome");
}

String input2 = "rac ecar";
boolean isPal2 = isPalindrome(input2);

if (isPal2) {
System.out.println(input2 + " is a palindrome");
} else {
System.out.println(input2 + " is not a palindrome");
}

}

private static boolean isPalindrome(String input) {

// this is the end of recursive. If length is 0 or 1 then stopping the process.
if (input.length() == 0 || input.length() == 1)
return true;

// comparing the first and last index values.
if (input.charAt(0) == input.charAt(input.length() - 1))

// calling again isPalindrome() method but we are not passing the complete
// string. Passing the remaining string after removing the first and last index.
// For each recursive call, we will be removing the compared characters using
// substring() method of string class.
return isPalindrome(input.substring(1, input.length() - 1));

return false;
}

}

Output:

racecar is a palindrome
rac ecar is not a palindrome

7. Conclusion


In this article, you have seen all possible ways to find a given string is a palindrome or not. But the effective way is not using any built-in API classes and reverse() method. Comparing the first and last character approach is the best one (i.e. section 5). The recursive approach is also good but it has multiple calls to string API methods. Otherwise, the recursive approach has to be considered.

You reached this point means you liked the article, please share with your friends on facebook or WhatsApp using below share options.

0 Comments