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 a.compareTo(b)doesn't compile ( int cannot be dereferenced)? I know that it compareTorequires objects, but I thought that autoboxing would automatically do inta Integerwhen necessary. Why in this case does not occur auto-boxing? And what other cases will this not happen?

+5
source share
1 answer

From the Oracle Autoboxing tutorial , two cases when boxing will happen 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.

, (a.compareTo(d)), .

​​ JCP , , .

+4

All Articles