Palindrome string in Java

String palindrome program in java

A String is said to be a Palindrome String if after reversing it, it results in the original string.

Alternatively, we could say: A string is a palindrome if reading it forwards or backwards produces the same sequence of characters.

Example: MADAM, EYE, RADAR, CIVIC, etc.

The basic logic for checking Palindrome String is to calculate its length and then reverse it using a loop construct by running a loop and extracting characters from (N-1)th position to 0th position. Store the same in another variable and the compare result with original string.

Algorithm

  1. Prompt the user to input a string.
  2. Store the string in a variable.
  3. Initialize another variable to store the reversed string.
  4. Use a loop to iterate through the characters of the original string in reverse order.
  5. Append each character to the reversed string as you iterate.
  6. Compare the reversed string to the original string.
  7. If the two strings are the same, print a message indicating that the original string is a palindrome.
  8. If the two strings are not the same, print a message indicating that the original string is not a palindrome.
  9. Exit the program.

Java Code:

/* Program to enter a String and check if it is Palindrome or not. */
import java.util.*;

class PalindromeString {
    public static void main() {
        Scanner inp = new Scanner(System.in);

        System.out.print("\n Enter String: ");
        String s = inp.nextLine();
        String z = "";
        char c;
        int i, k = s.length();

        for (i = (k - 1); i >= 0; i--) {
            c = s.charAt(i);
            z = z + c;
        }

        if (z.equals(s) == true)   // Comparing Both Strings
            System.out.println(s + " is a Palindrome String");
        else
            System.out.println(s + " is not a Palindrome String");
    }
}

Output:

Enter String: REFER
REFER is a Palindrome String
Palindrome string in Java