Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Character equals char autoboxed or unboxed in java? [duplicate]

Tags:

java

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?

like image 835
user1604064 Avatar asked Nov 22 '16 07:11

user1604064


1 Answers

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.

like image 85
Ted Hopp Avatar answered Oct 31 '22 01:10

Ted Hopp