In Java, the “equals()” method is used to identify the equality between two objects and their references. It is mostly used for comparing two values. This method belongs to the “Object” class, which is the super class of all the Java wrapper classes like Integer, Character, and so on. As a result, all wrapper class objects implement the equals() method of the Object class, and it wraps the primitive data types like Character holds the char primitive data type.
This post will go through the usage of the char equals() method in Java.
How to Use the char equals() Method in Java?
To compare the character-type objects, we will use the “equals()” method of the Character class. It takes an object or a reference of an object as a parameter and compares it with the other object. It gives a boolean value “true” if the compared values and their case are equal; otherwise, it gives “false”.
Syntax
The provided syntax is used for the “equals()” method:
The object “ch1” calls the equals() method by passing another object “ch2” as an argument for comparison.
Example 1
In this example, we will create two characters, “ch1” and “ch2”, and assign them the following values:
We will now call the “equals()” method with “ch1” character and pass “ch2” as an argument:
The output shows “false” which means the values of “ch1” and “ch2” are not equal as they have a different case:
Example 2
In this example, we will compare two characters with conditional statements. Here, we have two instances of the Character class, “ch1” and “ch2”:
Now, we will check whether these two character values are equal or not. For the specified purpose, we will add an “if” statement and call the “equals()” method to check if the “ch1” character equals “ch2”:
The output shows that the both character values and their case are equal:
We have gathered all the basic instructions about using char equals() method in Java.
Conclusion
In Java, you can use the char “equals()” method to compare two character values by passing a character as a parameter. It returns a boolean value, “true” or “false”, where true indicates the value and the case is equal, and false denotes its negation. The method is case sensitive; it will return false if one character is in lowercase and the other is in upper case. In this post, we explained the usage of the char equals method in Java with examples.