Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why widening beats both Boxing and var-args in Overloading of a method?

Tags:

java

I am preparing for a SCJP exam and when studying widening part it's given that widening beats both Boxing and Var-args in overloading but there is no clear explanation. Tried searching but didnt get any better answer.

One answer i got is because the compiler chooses the older style before it chooses the newer style. But I am not convinced.

Edit: I know widening is preferrd than boxing and var-args. but WHY is my question. of which i know one. any other reasons.

like image 542
GuruKulki Avatar asked Jan 24 '10 17:01

GuruKulki


3 Answers

Yes, the compiler "chooses the older style over the newer style", because of compatibility requirements. Imagine some code, written before Java 5 came out, that suddenly had a change of behaviour when compiled under Java 5! That would be bad.

Widening conversions have been around since the dawn of Java, but autoboxing and varargs are new to Java 5.

like image 89
Chris Jester-Young Avatar answered Oct 22 '22 21:10

Chris Jester-Young


Here is an example of it:

class Widen {

    private static void widen(long k) {
        System.out.println("Converted to long: " + k);
    }

    private static void widen(int ... k) {
        System.out.println("Converted to varargs: " + k);
    }

    private static void widen(Integer k) {
        System.out.println("Converted to Integer: " + k);
    }

    public static void main(String ... args) {
        int value = 3;
        widen(value);  // Output: Converted to long: 3
    }
}    

So all this means is that it will widen before autoboxing and using varargs. If we took out the method of widen with the long parameter, it would have chosen the autoboxing before the varargs.

like image 45
Turing Avatar answered Oct 22 '22 21:10

Turing


The compiler has to keep compatibility with previous versions of Java. On top of that the compiler chooses the most performant / smallest change to the argument. Promoting to another primitive beats creating wrapper object and that beats creating an array with regards to memory usage and performance.

like image 1
rsp Avatar answered Oct 22 '22 23:10

rsp