In this post we will go through the java string program to check if a String is Palindrome or not. We will also run the examples and corresponding output.
A string is called a palindrome if the reverse of that string is same as the original string. For example: level, madam, etc.
Problem :
simple example of the problem –
Example 1:
Input : str = “abba”
Output : Yes, the given string is a palindrome.
Example 2:
Input : str = “Hello”
Output : No, this string is not a palindrome.
Explanation:
For the string “abba“, you can see that if you read the string from backwards or forward, it reads the same. So, this string is a palindrome.
But for the string “Hello“, it’s not a palindrome as it doesn’t read the same for the backwards and forward.
Algorithm:
- take or input a String.
- take a variable “rev” to store reverse value of string.
- get the length of string
- Take a i loop start it from i=s.length()-1 to i>=0
- .Then get each characterusing charAt() method and store it in rev variable.
- if rev variable is equal to string then print “String is palindrome”.
- Else print “String is not palindrome”.
class Main{ public static void main(String[]args){ String s ="madam"; String rev=""; int len=s.length(); for(int i=len-1;i>=0;i--){ rev=rev+s.charAt(i); } if(s.equals(rev)){ System.out.println(s+" is palindrome"); } else{ System.out.println(s+ " is not palindrome") } } }
Output:
madam is palindrome
other java practice programs:
Java Program to Check a Number is Palindrome or Not