Question

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?

Was it helpful?

Solution

From the Oracle tutorial on Autoboxing, the two cases where boxing will occur are, when primitives are:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top