1.

Write a program to check whether the given input string is a palindrome.

Answer»

When a string is the same when read right to LEFT or left to right, it is called a palindrome. To assess whether a string is a palindrome or not, we first reverse the string and then compare the reversed string with the original ONE. Below is a JAVA program that will check if a string is a palindrome.

public class PalindromeChecker { public STATIC VOID main (String[] args)  { String str1 = "rotator"; String revstr = reverseString(str1); //revstr=reverse string if (str1.equals(revstr))  { System.out.println("The string" + str1 + " is a Palindrome String."); }  else  { System.out.println("The string" + str1 + " is not a Palindrome String."); } } // a method for reversing a string public static String reverseString(String str2)  { String revstr = ""; for (int i = str2.length() - 1; i >= 0; i--)  { revstr += str2.charAt(i); } return revstr; }}

Output:

The string rotator is a Palindrome String.

As shown in the above example, we have a string "Rotator" stored in string object "str1" and another string object "revstr" to store the reverse of str1. To check whether two strings are equal or not, we have used the equals() method. 



Discussion

No Comment Found