Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java no autoboxing for int for compareTo method?

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?

like image 477
Kailua Bum Avatar asked Oct 05 '22 23:10

Kailua Bum


1 Answers

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.

like image 170
Perception Avatar answered Oct 10 '22 02:10

Perception