Java Program to Check Whether Given String is a Palindrome

Palindrome is a string, which when read in both forward and backward way is same.

Example:
Example: madam, lol, pop, radar, rubber, etc.

Palindrome String Check Program in Java

This Java program asks the user to provide a string input, and checks it for the Palindrome String.

  • Scanner class and its function nextLine() is used to obtain the input, and println() function is used to print on the screen.
  • Scanner class is a part of java.util package, so we required to import this package in our Java program.
  • We also required to create object of Scanner class to call its functions.
Example:
import java.util.Scanner;
 
class ChkPalindrome
{
   public static void main(String args[])
   {
      String str, rev = "";
      Scanner sc = new Scanner(System.in);
 
      System.out.println("Enter a string:");
      str = sc.nextLine();
 
      int length = str.length();
 
      for ( int i = length - 1; i >= 0; i-- )
         rev = rev + str.charAt(i);
 
      if (str.equals(rev))
         System.out.println(str+" is a palindrome");
      else
         System.out.println(str+" is not a palindrome");
 
   }
}
Program Output:
Enter a string:
radar

radar is a palindrome
Explanation:

To check if a string is a palindrome or not, a string needs to be compared with the reverse of itself.

Consider a palindrome string: radar,

Palindrome String

---------------------------
index: 0 1 2 3 4

value: r a d a r
---------------------------


Here are few other related articles for you to read:

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.