Java Programming Examples Tutorial Index

Java String Programs

A palindrome is a string, which, when read in both forward and backward ways is the same.



Example:

Example: madam, lol, pop, radar, 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 an 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
---------------------------



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram