Since String
is an object, we use string.equals(string)
to check equality. However, when comparing char
values, we use char1 == char2
instead of char1.equals(char2)
.
Why is that? Does char equals in Java work differently from String comparison?
The key reason why char.equals() doesn’t work is that char is a primitive type, not an object. In Java, primitives don’t have methods like .equals(), so you must use == for comparison.
char a = 'A';
char b = 'A';
if (a == b) {
System.out.println("Both characters are equal!");
}
This works because char values are just 16-bit Unicode numbers under the hood. == directly compares their numeric values, making it both correct and efficient.
The first answer is absolutely right for primitive char, but if you’re dealing with Character objects (the wrapper class for char), then .equals() does work!
Character a = 'A';
Character b = 'A';
if (a.equals(b)) {
System.out.println("Characters are equal!");
}
This works because Character is an object, and objects have an equals() method. But keep in mind that auto-boxing can sometimes cause unexpected behavior with == when comparing Character objects, so .equals() is the safe bet here.
Both previous answers are correct, but what if you need a case-insensitive comparison? Here’s how you can do it:
char a = 'A';
char b = 'a';
if (Character.toLowerCase(a) == Character.toLowerCase(b)) {
System.out.println("Characters are equal (ignoring case)!");
}
This approach is useful when comparing characters in case-insensitive scenarios, like checking user input.
Since Character.toLowerCase() and Character.toUpperCase() convert characters reliably, it’s a great way to avoid incorrect comparisons due to case differences.