class Test{
public static void main(String[] args){
int a = 1;
int b = 5;
Integer c = new Integer(1);
Integer d = 5; //autoboxing at work
System.out.println(c.compareTo(d));
System.out.println(a.compareTo(b));
}
}
Why doesn't a.compareTo(b)
compile (int cannot be dereferenced
)? I know that compareTo
requires objects, but I thought autoboxing would automatically make an int
an Integer
when necessary. Why doesn't autoboxing occur in this case? And what other cases will it not occur?
From the Oracle tutorial on Autoboxing, the two cases where boxing will occur are, when primitives are:
The expression being evaluated in your example (a.compareTo(d)
) does not fall in any one of those scenarios.
Theres some interesting additional information in the JCP proposal for autoboxing, describing the mechanics and rules for assignment conversion, method invocation conversion, and casting conversion.
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