Automatic unboxing of Java wrapper classes

topic:

Integer i =  42 ;
Long l = 42l;
Double d =  42.0 ;

The following is true

 

A.(i == l)

 

B.(i == d)

 

C.(l == d)

 

D.i.equals(d)

 

E.d.equals(l)

 

F.i.equals(l)

 

G.l.equals(42L)

 

Answer: G

Analysis: When comparing the same type, such as Integer and int, Long and long, when == is compared, it will be automatically unboxed; when comparing different types, if one of them is a non-wrapper class, it will be automatically unboxed. If both parties are wrapper classes, they will not be unboxed and cannot be compared, and an error will be reported when compiling, so both ABCs are wrong. DEF calls the equals method, which returns false because this method compares types first, and i , d , and l are different types. Option G will automatically box 42L into a Long type, so when the equals method is called, the type is the same and the value is the same, so it returns true.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324614038&siteId=291194637