Check the given String is Palindrome or not?
If a string is palindrome, it gives the same string even after reversing it.
For example, malayalam, madam, liril etc.., are palindromes.
The following steps can be followed to check the string:
- Let the string be 'str'.
- Preserve a copy of the original string 'str' in another string 'temp'.
- Convert the string 'str' into a StringBuffer object 'sb'.
- Reverse the string in sb.
- Store the reversed string in 'str' again.
- Now, compare the original string 'temp' with the reversed string 'str' . If they equal the given string is palindrome, else not a palindrome.
We are converting a String into StringBuffer to use the reverse() method of StringBuffer class.
It is not possible to use methods of a class on the objects of another class.
Java code to check if the given string is palindrome or not:
import java.io.*;
class Programming9
{
public static void main (String args[]) throws IOException
//IO Exception will thrown if an I/O errors occur
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); //accept String from keyboard
System.out.println ("enter the String:");
String str = br.readLine (); // read from BufferReader class
String temp = str; // converting the string into StringBuffer
StringBuffer sb = new StringBuffer (str);
sb.reverse (); //reverse String into StringBuffer
str = sb.toString (); //convert StringBuffer into a String
if (temp.equalsIgnoreCase (str)) //compare original string available in temp with this reversed String
System.out.println (temp + " is palindrome");
else
System.out.println (temp + " is not palindrome");
}
}
Output:
enter the String: Malayalam Malayalam is palindrome
enter the String: madam madam is palindrome
Palindrome Other Articles