In: Computer Science
Meant to be written in Java JDK 14.0
A String object is called palindrome if it is same when read from the front and the end. For example, String “abcba” is palindrome, while “12322” is not. Write Java program to check a String object of 5 characters is palindrome or not: (a) The comparison is case sensitive (b) The comparison is case insensitive
1)
// java program for checking string polindrome(Case
sensitive)
import java.util.*;
import java.util. Scanner;
class Main
{
public static void main(String args[])
{
String orig, reverse = "";
Scanner scann = new Scanner(System.in);
// taking string from user
System.out.println("Enter a string to check : ");
orig = scann.nextLine();
// finding length of string
int length = orig.length();
if(length==5)
{
for (int i =length - 1; i >= 0; i--)
// reversing original string
reverse = reverse + orig.charAt(i);
// equals() wil check whether both are equal or not
if (orig. equals(reverse)) // cheking equal or not
System.out.print("It is a palindrome");
else
// if both are not equal then it is not a polindrome
System.out.print("It isn't a palindrome.");
}
else
{
// asking to enter length 5 string only
System.out.print("Enter String of length 5 only : ");
}
}
}
output
2)
// java program for checking string polindrome(Case
sensitive)
import java.util.*;
import java.util. Scanner;
class Main
{
public static void main(String args[])
{
String orig, reverse = "";
Scanner scann = new Scanner(System.in);
// taking string from user
System.out.println("Enter a string to check : ");
orig = scann.nextLine();
// finding length of string
int length = orig.length();
if(length==5)
{
for (int i =length - 1; i >= 0; i--)
// reversing original string
reverse = reverse + orig.charAt(i);
// toLowerCase() will change all smalls to capital letters.
orig=orig.replaceAll("[^A-Za-z]", ""). toUpperCase();
reverse=reverse.replaceAll("[^A-Za-z]", "").toUpperCase();
// equals() wil check whether both are equal or not
if (orig. equals(reverse)) // cheking equal or not
System.out.print("It is a palindrome");
else
// if both are not equal then it is not a polindrome
System.out.print("It isn't a palindrome.");
}
else
{
// asking to enter length 5 string only
System.out.print("Enter String of length 5 only : ");
}
}
}
output