×

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 Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.