×

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 List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.