Check If A String Is Palindrome Or Not Ignoring The Case Of Characters In Java

By Saruque Ahamed Mollick

In this post, we are going to learn if a string is a palindrome or not ignoring the case of the characters used to build the string.

What is a palindrome word?

A word is said to be a palindrome if the reverse of the word is to be same as the unreversed word. (e.g, rotator)

It is really very easy to check a String is either palindrome or not, But when you need to check it ignoring the characters are in lower case or not then it will be something called tricky program.
for example- “madam” is a palindrome word as if we reverse the string “madam”, It will still be unchanged. It is called as a palindrome word.
But assume that you have a string like this “Madam”, Where M is in upper case. Then it will not be a palindrome anymore as if we simply make it reverse, the string will be like this “Madam” and both the strings are not same for a compiler.



So in this java post, we are going to build a program which will check if a string is palindrome or not ignoring this character case issue (that means it will ignore the case of characters and will return true value if the string is palindrome irrespective of the character cases either it will return false if the string is not palindrome)

Java Program To Check A Number is Palindrome or Not

import java.util.*;

public class codespeedy
{
  private static final String Text = null;

  public static boolean Palindrome(String Text) {
    Scanner input=new Scanner(System.in);
    System.out.println("Enter a word");
    Text=input.next();
     System.out.println(Text);
    Text = Text.toLowerCase();
       
        String reverse = new StringBuilder(Text).reverse().toString();
        if( Text.equals(reverse)){
        	return true;
        }else{
        	return false;
        }
    }
    
    public static void main(String[] args) {
        System.out.println(Palindrome(Text));
    }
}

Output:

Enter a word
Madam
Madam
true

 

Enter a word
Codespeedy
Codespeedy
false

How To Reverse String In Java in Different Ways

 

Methods used in this program:

StringBuilder(Text) – By this method, we have initialized a new string with the value of Text String

reverse() – This method is used to reverse a String

Text = Text.toLowerCase(); – toLowerCase() method converts the whole String into lower case letters. (you can use upper case too, out main intention is to create a String which will have all letters in the same case either upper or lower)

 

Leave a Reply

Your email address will not be published. Required fields are marked *