Learn Palindrome Program in Java

A palindrome is a word, phrase, or string of characters that reads exactly the same both forward and backward. It’s a string that, to put it simply, is written the same way from right to left and left to right. In this blog, we will understand how to write a palindrome program in Java along with different methods and more.

Method 1: Check if a string is a Palindrome or not in Java

import java.util.Scanner;

public class PalindromeExample {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a string: ");
       String str = sc.nextLine();
       String reverse = "";
       for(int i = str.length()-1; i>=0; i--) {
           reverse = reverse + str.charAt(i);
       }
       if(str.equalsIgnoreCase(reverse)) {
           System.out.println(str + " is a palindrome");
       }
       else {
           System.out.println(str + " is not a palindrome");
     }
   }
}

Explanation of code for Palindrome Program, using a predefined String

The code is a Java program to check whether a given string is a palindrome or not. Here is an explanation of the code along with the output:

  1. Importing necessary package: We are importing the Scanner class, which accepts user input, from the java.util package.
  2. Declaring and initializing variables: We declare and set up three variables: The variable “sc” represents the Scanner class, which we use to read user input. We store the input string entered by the user in the variable “str”. We keep the reversed string of “str” in the variable “reverse”.
  3. Reversing the input string: Using a for loop, we iterate through the str string backwards and store the characters in the resultant reverse string.
  4. Checking for Palindrome: We are checking if the original string str is equal to the reversed string reverse, and if they are equal, we print that the string is a palindrome or not.

Output: 

Enter a string:
madam
madam is a palindrome

Let’s dive into the Java Palindrome Program’s second variant further. 

Check out our blog on Prime Number in Java here!

Method 2: Check whether a string in Java is a palindrome, without using a predefined String

import java.util.Scanner;

public class PalindromeExample {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a string: ");
       String str = sc.nextLine();
       int length = str.length();
       boolean isPalindrome = true;
       for(int i=0; i<length/2; i++) {
           if(str.charAt(i) != str.charAt(length-i-1)) {
               isPalindrome = false;
               break;
           }
       }
       if(isPalindrome) {
           System.out.println(str + " is a palindrome");
       }
       else {
           System.out.println(str + " is not a palindrome");
       }
   }
}

Explanation of code for Palindrome Program, without using a predefined String.

The above Java code is a program to check whether a given string is a palindrome or not. Here is the explanation of the code:

  1. Importing the required package: This line imports the Scanner class from the Java.util package, which we use to accept user input.
  2. Declaring and initializing variables: We are declaring and setting three variables to their initial values.:
    sc: In order to read user input, this variable is an instance of the Scanner class.
    str: We keep the input string that the user entered in this variable.
    length: The length of the str string is kept in this variable for future reference.
    isPalindrome: We determine whether or not the “str” string is a palindrome and store the result in this variable.
  3. Checking for Palindrome: To compare the characters from both ends of the str string, we are using a for loop to traverse half of the string. When a character from a string’s beginning does not match a character from its ending, we know the string is not a palindrome and set the isPalindrome variable to false. When we encounter an unbalanced pair of characters, we immediately exit the loop. 
  4. Printing the results: Based on the value of the isPalindrome variable, we are printing a message indicating whether the original string, str, is a palindrome or not. Using the aforementioned code, you can quickly determine whether a string is a palindrome or not. We decrease the number of required iterations by considering only half of the string.

Output:

Enter a string:
racecar
racecar is a palindrome
Enter a string:
hello
hello is not a palindrome

Check out  Python Interview Questions and Answers, Now!

Method 3: Palindrome Program using While Loop

The following is an illustration of a Java while loop-based palindrome program:

import java.util.Scanner;
public class PalindromeWhileLoop {
  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string: ");
      String str = sc.nextLine();
      String reverse = "";
      int length = str.length();
      int i = length - 1;
      while (i >= 0) {
          reverse = reverse + str.charAt(i);
          i--;
      }
      if (str.equals(reverse)) {
          System.out.println(str + " is a palindrome");
      } else {
          System.out.println(str + " is not a palindrome");
      }
  }
}

Explanation of code for Palindrome Program using While Loop

The while loop enables code to run repeatedly depending on a specified Boolean condition.

In this program, we ask the user to enter a string before using the Scanner class to read it. Next, we create the reverse string, an empty string that will be used to store the reversed string. We then determine the length of the input string, and initialize a variable named “i” to “length – 1”. The input string’s characters are then iterated over using a while loop in reverse order, beginning with the last character and moving backward. We add the current character to the reverse string and decrease the value of “i” each time.

When the while loop is finished, we use the equals() method to compare the original input string str and the reversed string reverse. If they match, we print a message stating that the input string is a palindrome. If they do not match, we print a message stating that the input string is not a palindrome.

Output:

Here’s an example output of this program:

Enter a string:
racecar
racecar is a palindrome

Get a Complete list of Online Certification Courses in India here!

Method 4: Palindrome Program using For Loop

The for loop, as a control flow statement, enables the repetition of code based on a specified condition. Here is a Java program that uses a for loop to generate palindromes:

import java.util.Scanner;
public class PalindromeForLoop {
  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string: ");
      String str = sc.nextLine();
      int length = str.length();
      boolean isPalindrome = true;
      for (int i = 0; i < length / 2; i++) {
          if (str.charAt(i) != str.charAt(length - i - 1)) {
              isPalindrome = false;
              break;
          }
      }
      if (isPalindrome) {
          System.out.println(str + " is a palindrome");
      } else {
          System.out.println(str + " is not a palindrome");
      }
  }
}

Explanation of code for Palindrome Program using for Loop:


This program prompts the user to enter a string and then reads the input using the Scanner class.
Then, the program determines the length of the input string and sets the Boolean variable “isPalindrome” to true. The second step involves iterating over the first half of the input string using a for loop to compare each character with its corresponding character from the string’s end. We set the isPalindrome variable to false and exit the loop if the characters do not match.

Output:

Enter a string: racecar
racecar is a palindrome

Real-life Applications of Palindrome Program in Java

A palindrome program in Java can be applied in various real-life scenarios, including:

Puzzles and Games: Palindromic sequences are often used in puzzles and games. A palindrome program can generate or verify these sequences, providing a tool for game developers to create engaging content.

Data Validation:

Serial Numbers and Product Codes: Some systems use palindromic sequences in serial numbers or product codes to ensure they are entered correctly. For example, checking if a serial number is the same forwards and backwards can prevent errors.

Bioinformatics:

DNA Sequence Analysis: Palindromic sequences in DNA can indicate important biological markers. A palindrome program can help identify these sequences, which are crucial for understanding genetic structures and functions.

Cybersecurity:

Password Checking: Palindromic passwords can be a specific security feature. A palindrome program can verify if a password follows this rule, adding an extra layer of security.

Text Processing:

Palindrome Detection in Text: In applications like text editors or messaging apps, a palindrome program can highlight palindromic phrases, which might be of interest for stylistic or linguistic analysis.

Symmetry in Architecture and Design:

Design Validation: In fields like architecture and design, ensuring symmetry can be important. A palindrome program can verify if certain designs or structures are symmetrical, which is essential for aesthetic and functional purposes.

Entertainment and Gaming:

Puzzles and Games: Palindromic sequences are often used in puzzles and games. A palindrome program can generate or verify these sequences, providing a tool for game developers to create engaging content.

We hope you found our blog post on “Palindrome Program in Java” informative and beneficial. To keep upscaling your coding skills, Check out Newtum’s website and explore our online coding courses covering Java, Python, PHP, and more.

About The Author

Leave a Reply