How can I check if a given string is a palindrome using Java?

1 Answers
Answered by suresh

How to check if a given string is a palindrome using Java?

To check if a given string is a palindrome in Java, you can follow these steps:

  1. Declare a string variable to store the given string.
  2. Create a new string variable to store the reverse of the given string.
  3. Use a loop to iterate through each character of the given string and append them in reverse order to the reverse string variable.
  4. Compare the given string with the reverse string using the equals() method.
  5. If the two strings are equal, then the given string is a palindrome.

Here's an example Java code snippet to check if a given string is a palindrome:

```java
public class PalindromeCheck {
public static boolean isPalindrome(String str) {
String reverse = "";

for (int i = str.length() - 1; i >= 0; i--) {
reverse += str.charAt(i);
}

return str.equals(reverse);
}

public static void main(String[] args) {
String input = "madam";

if (isPalindrome(input)) {
System.out.println("The given string is a palindrome.");
} else {
System.out.println("The given string is not a palindrome.");
}
}
}
```

By following these steps and using the provided code snippet, you can easily check if a given string is a palindrome in Java.

Answer for Question: How can I check if a given string is a palindrome using Java?