8

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?

user1604064
  • 809
  • 1
  • 9
  • 29

4 Answers4

8

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.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
5

The equals method you are calling (in s.equals('y')) is a method of the Character class that takes an Object argument. Therefore the char argument you are passing to it must be boxed.

There is no need for unboxing, since the value member of the Character class (whose type is a char) is used for the actual comparison :

public boolean equals(Object obj) {
    if (obj instanceof Character) {
        return value == ((Character)obj).charValue();
    }
    return false;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
2

When you do this:

s == 'y' 

Character 's' will unbox itself to char.

and when you do this:

s.equals('y') 

'y' will be autobox because equals() is method of the Character like @Eran said.

msagala25
  • 1,806
  • 2
  • 17
  • 24
1

s == 'y' is unboxed, and s.equals('y') is auto boxed. To check it just try to put a break point inside equals method of the Character class and debug your program, you can find out it is auto boxed or unboxed. First case you will not see control getting in, but it is in the second case.

Sagar U
  • 86
  • 4