Java code to check the given string is palindrome or not

Here we are going to check whether the given string value is palindrome or not. We will declare two String as "original" and "reverse". Then import the Scanner object which will enable us to enter any String value into the console. In my example I'm going to enter "mom" as an original String and which is obviously a palindrome.

Palindrome definition:

The string value should be the same whether we read from left hand side or from right hand side.
Palindrome exp: mom, dad
Non palindrome exp: java, string etc.

import java.util.*;
public class PalindromeTest {
    public static void main(String args[]) {         String original, reverse = "";         Scanner in = new Scanner(System.in);         System.out.print("Enter a string to check if it is a palindrome: ");         original = in.nextLine();         int length = original.length();         for (int i = length - 1; i >= 0; i--)             reverse = reverse + original.charAt(i);         if (original.equals(reverse))             System.out.println("Entered string is a palindrome.");         else             System.out.println("Entered string is not a palindrome.");     } }

Output:

Enter a string to check if it is a palindrome: mom
Entered string is a palindrome.

5 comments: