Way2Java

Use equalsIgnoreCase() with Character objects

We have seen earlier comparing two Character objects with equals() method. It was case sensitive comparison. Infact, Character class does not have a method like equalsIgnoreCase(). But String has one. Apply a small technique to do case insensitive comparison with characters.

Just convert both the characters in comparison either to uppercase or lowercase. For this use toUppertCase() or toLowerCase() methods and then compare.

Following "Use equalsIgnoreCase() with Character objects" code illustrates.
public class CharacterFunctionDemo
{
  public static void main(String args[])
  {
    System.out.println("A and a are same: " + new Character(Character.toLowerCase('A')).equals(new  Character(Character.toLowerCase('a')))); // true
  }
}



Output screenshot of Use equalsIgnoreCase() with Character objects

The above statement can be modified as follows for better understanding to Beginners.

Character c1 = new Character(Character.toLowerCase('A'));
Character c2 = new Character(Character.toLowerCase('a'));
System.out.println(c1.equals(c2));

Pass your comments and suggestions to improve the quality of this tutorial "Use equalsIgnoreCase() with Character objects".

Another way is shown but it may be used rarely.

public class Demo  
{
  public static void main(String args[])    
  {
    char ch1 = 'A';   
    char ch2 = 'A'; 
    char ch3 = 'B';

    System.out.println("A and A are equal: " + (""+ch1).equals(""+ch2));   // prints true
    System.out.println("A and B are equal: " + (""+ch1).equals(""+ch3));   // prints false
  }
}

Here equals() method of String class is used to compare two characters. Or you can use equalsIgnoreCase() method for case-insensitive comparison.

The above program is a mater of interest and not used practically as equals() you can use directly with character objects. See equals() example in the same series.