×

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 Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

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.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 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.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 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.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.