Char Comparison Java

For comparing two characters logical equals (==) operator can be used. Alternatively, the chars can be passed to Character constructor and compared with equals() method. The following program illustrates.

Program on Char Comparison Java
public class CharComparison
{
  public static void main(String args[])
  {
     char ch1 = 'A';
     char ch2 = 'A';
     char ch3 = 'B';
                                                //  using == 
     System.out.println(ch1 == ch2);
     System.out.println(ch1 == ch3);

     Character charObject1 = new Character(ch1);
     Character charObject2 = new Character(ch2);
     Character charObject3 = new Character(ch3);

     System.out.println(charObject1.equals(charObject2));
     System.out.println(charObject1.equals(charObject3));
   }
}


Char Comparison Java
Output screenshot on Char Comparison Java

Two characters can be compared using logical equals (==) operator and equals() method. These will evaluate to a boolean value of true if they are same, else false.

equals() method is to be used with objects but not with primitive data types. For this reason, the char ch1, ch2 and ch3 are passed to Character class constructor, and then compared with equals() method.

Pass your comments and suggestions on this tutorial "Char Comparison Java" to improve quality of content.

Would you like to know about packages?

1. Predefined Packages – Java API
2. Creating Custom-Defined Packages
3. Access Specifiers – Accessibility Permissions & Restrictions