Java Character equals() Example


Like Math class comes with many methods to do simple arithmetic calculations, java.lang.Character class comes with many methods to manipulate characters like from lowercase to uppercase and to find what type of Character is like uppercase letter or a digit etc. Character class is a boon to Java Programmer to do with characters in coding.

We know earlier how to use equals() and equalsIgnoreCase() with respect to strings and now let us use the same equals() method with characters to compare two character objects. We will see how to use equalsIgnoreCase() with characters later (infact, there is no equalsIgnoreCase() method in Character class).

Following is the signature of Character class as defined in java.lang package.

public final class Character extends Object implements Serializable, Comparable

Character class was introduced in Java API with JDK 1.0, the starting version of Java.

Following is the method signature as defined Character class

  • public boolean equals(Object obj): This method compares two Character objects are same or not. If the two Character objects represent the same char value, then the method returns true else false. Infact, Character class overrides the equals() method of Object class in the style to compare two Character objects. Similarly, equals() method is overridden by String class to compare two string values.

With this introduction let us go to an example.

Following Java Character equals() Example illustrates.
public class CharacterFunctionDemo
{
  public static void main(String args[])
  {
    Character c1 = new Character('A');
    Character c2 = new Character('A');
    Character c3 = new Character('B');

    System.out.println("c1 and c2 objects both representing A are same: " + c1.equals(c2)); 
    System.out.println("c1 and c3 objects representing A and B are same: " + c1.equals(c3)); 
  }
}


Java Character equals() Example
Output screenshot on Java Character equals() Example

Guess the output for the following Character objects

public class CharacterFunctionDemo
{
  public static void main(String args[])
  {
    Character c1 = null;
    Character c2 = null;

    System.out.println("c1 and c2 objects representing null value are same: " + c1.equals(c2)); 
  }
}

Java Character equals() Example

The above code compiles but throws NullPointerException at runtime.

Leave a Comment

Your email address will not be published.