Check palindrome string in java

In this tutorial we will write different solutions for palindrome string in java. In is one of the questions asked in interviews.

What is a palindrome?

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction. Here is an example of palindrome string.

Palindrome String in Java

Palindrome String

Write a program to check palindrome string in java

<br />
/**<br />
 *<br />
 * @author programtalk.com<br />
 *<br />
 */<br />
public class CheckPalindrome {<br />
	boolean isPalindrome(String input) {<br />
		int stringLength = input.length();<br />
		int indexLastElement = stringLength -1;<br />
		for (int i = 0; i &lt; stringLength / 2; i++) {<br />
			if (input.charAt(i) != input.charAt(indexLastElement - i)) {<br />
				return false;<br />
			}<br />
		}<br />
		return true;<br />
	}</p>
<p>	public static void main(String[] args) {<br />
		CheckPalindrome checkPalindrom = new CheckPalindrome();<br />
		System.out.println(&quot;madam is plaindrome : &quot; +checkPalindrom.isPalindrome(&quot;madam&quot;));<br />
		System.out.println(&quot;running is palindrome : &quot;+checkPalindrom.isPalindrome(&quot;running&quot;));<br />
	}<br />
}<br />

Output

<br />
madam is plaindrome : true<br />
running is palindrome : false<br />

Check Palindrome using StringBuilder.reverse()

<br />
/**<br />
 *<br />
 * @author programtalk.com<br />
 *<br />
 */<br />
public class CheckPalindrome {<br />
	boolean isPalindrome(String input) {<br />
		return input.equals(new StringBuilder(input).reverse().toString());</p>
<p>	}</p>
<p>	public static void main(String[] args) {<br />
		CheckPalindrome checkPalindrom = new CheckPalindrome();<br />
		System.out.println(&quot;madam is plaindrome : &quot; + checkPalindrom.isPalindrome(&quot;madam&quot;));<br />
		System.out.println(&quot;running is palindrome : &quot; + checkPalindrom.isPalindrome(&quot;running&quot;));<br />
	}<br />
}<br />

StringBuilder().reverse() reverses the String and then checking for equality does the palindrom check. But this solution is not very efficient, for more see here

Note :  Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

You may also be interested in:

Like this post? Don’t forget to share it!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.