Palindrome string in Java
Written by
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
- Prompt the user to input a string.
- Store the string in a variable.
- Initialize another variable to store the reversed string.
- Use a loop to iterate through the characters of the original string in reverse order.
- Append each character to the reversed string as you iterate.
- Compare the reversed string to the original string.
- If the two strings are the same, print a message indicating that the original string is a palindrome.
- If the two strings are not the same, print a message indicating that the original string is not a palindrome.
- 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