×

String Palindrome Program in Java

String Palindrome Program in Java

The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and backward (right to left) without changing the meaning of the word or phrase. For example, madam, tattarrattat, noon, civic, racecar, mom, level, etc. In this section, we will create Java programs with different approaches and check the string is palindrome or not.

There are various ways to check whether a string is a palindrome or not. Let’s start with the simple iterative approach using Java-for loop.

Iterative Approach

Filename: PalindromeExample.java

public class PalindromeExample
{             
public static void main(String argvs[])
{
               String str = "madam"; // string to be check
               int size = str.length(); // finds the length of the input string
               boolean isPalindrome = true; // we assume the string is palindrome.
               for(int i = 0; i < size / 2; i++)
               {
                               if(str.charAt(i) == str.charAt(size - i - 1))
                                              continue; // characters got matched, moving to next iteration
                               else
                               {
                                              // Setting the flag isPalindrome to false as the given string is
                                              // not a palindrome.
                                              isPalindrome = false;
                                              break; // terminate the execution of the loop
                               }                                                          
               }
               // Displaying the outcome
               if(isPalindrome)
                               System.out.println("The string " + str + " is a palindrome.");
               else
                               System.out.println("The string " + str + " is not a palindrome.");
}
}

Output:

The string madam is a palindrome.

Explanation: First, we compare the first character with the last character, the second character with the second last character, the third character with the third last character and so on, of the input string. If we found a mismatch anywhere while making the comparison, we can say that the given string is not a palindrome. Otherwise, it is a palindrome.

Two-Pointer Approach

Filename: PalindromeExample1.java

public class PalindromeExample1
{             
public static void main(String argvs[])
{
               String str = "madam"; // Input string
               int size = str.length(); // Calculating the length of the input string
               int ptr1 = 0, ptr2 = size - 1; // two pointers
               boolean isPalindrome = true; // we assuming that the string is palindrome
                while(ptr1 < ptr2)
               {
                               if(str.charAt(ptr1) == str.charAt(ptr2))
                               {
                                              ptr1++; // moving ptr1 one step forward
                                              ptr2--; // moving ptr2 one step backward
                               }
                               else
                               {
                                              // Setting the flag isPalindrome to false as the given string is
                                              // not a palindrome.
                                              isPalindrome = false;
                                              break; // Coming out of the loop
                               }                                            
               }
               // Displaying the outcome
               if(isPalindrome)
                               System.out.println("The string " + str + " is a palindrome.");
               else
                               System.out.println("The string " + str + " is not a palindrome.");
}
}

Output:

The string madam is a palindrome.

Explanation: In the above program, we have taken two pointers, namely, ptr1 and ptr2. The first pointer, ptr1, points to the first letter of the input string and the second pointer, ptr2, points to the last character of the input string. Now, we start the comparison of the characters pointed by those two pointers. If at any place a mismatch is found, the loop terminates and prints string is not palindrome. Else, the input string is a palindrome.

Built-in Method Approach

Filename: PalindromeExample2.java

public class PalindromeExample2
{             
public static void main(String argvs[])
{
               String str = "madam"; // Input string
               String cpyStr = str; // Creates a copy of the given string
               StringBuilder input = new StringBuilder(); // Creating an object of StringBuilder
               input.append(str); // Appending the input string      
               input.reverse(); // Reversing the input string
               // Comparing the modified string with its copy and displaying the result
               if(cpyStr.equals(input.toString()))
                               System.out.println("The string " + str + " is a palindrome.");
               else
                               System.out.println("The string " + str + " is not a palindrome.");
}
}

Output:

The string madam is a palindrome.

Explanation: Since the Java String class does not contain the reverse() method, Therefore, we took the help of the Java StringBuilder class. Using the reverse() method of the Java StringBuilder class, we reverse the input string. Finally, we make a comparison between the copy of the original string and its reversed form and displaying the result accordingly.

Recursive Approach

Filename: PalindromeExample3.java

public class PalindromeExample3
{             
// Method for finding whether the input string is a palindrome or not
static boolean isPalindrome(String input, int start, int end)
{
               // Handling base case
               if(start >= end) return true;
               if(input.charAt(start) == input.charAt(end))
                   // characters matched! Hence, recursively invoking the method
                   return isPalindrome(input, start+1, end - 1);
               // Mismatch found! Hence, return false.   
               return false;
}
public static void main(String argvs[])
{
               String str = "maple"; // Input string
               int size = str.length(); // Calculating size of the input string
               // Invoking boolean method isPalindrome() and displaying the result
               // accordingly
               if(isPalindrome(str, 0, size - 1))
               {
                               System.out.println("The string " + str + " is a palindrome.");
               }
               else
               {
                               System.out.println("The string " + str + " is not a palindrome.");
               }
}
}

Output:

The string maple is not a palindrome.

Explanation: We have used the concept of two pointer approach here. The start and end arguments of the isPalindrome() method point to the first and last character of the given string. If we find a mismatch, we come out from the recursion and return false. If the characters, pointed by the first pointer and the second pointer, match, we move further to explore the next set of characters, and we continue to do so until we reach the base case or find a mismatch.


Related Topics

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.