I'm thinking about this easy code:
Character s = 'n';
System.out.println(s == 'y');
System.out.println(s.equals('y'));
s = 'y';
System.out.println(s == 'y');
System.out.println(s.equals('y'));
with result
false
false
true
true
So the result is good but, how does this comparing work? Is Character object unboxed to char or chat is autoboxed to Character?
In the case of the ==
test, the Java Language Specification, Section 15.21, explains that the Character
is unboxed to a char
(a numeric type).
The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type.
And in §15.21.1:
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
In the case of equals()
, the char
value is boxed to a Character
, since the argument to equals()
needs to be a reference type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With