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:
- Declare a string variable to store the given string.
- Create a new string variable to store the reverse of the given string.
- Use a loop to iterate through each character of the given string and append them in reverse order to the reverse string variable.
- Compare the given string with the reverse string using the equals() method.
- 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.
Please login or Register to submit your answer