2

I know there are questions very similar to this one but pardon my ignorance, I still don't get it : (
The Java compiler chose widening over boxing for backwards compatibility.
But why does Java choose box-then-widen when it has to do two fold conversion ?

public class OverloadingTest1 {

public static void go(Long x){
    System.out.println("OverloadingTest1.go(Long x) : " + x.longValue());
}

public static void main(String[] args){

    byte i = 5;

    go(i);
}

}

Of course, this would fail to compile because even if the Java compiler widened and then boxed because it wouldn't have passed a IS-A test(Short/Integer is not Long).
But what if I changed the code to this ?

public static void main(String[] args){

        int i = 5;

        go(i);
    }

IF the Java compiler had chosen widen-then-box, it could have worked but in Java, you can box-then-widen , not widen-then-box.

My question is, why suddenly choose boxing first and then widening when doing one fold conversion it chose widening over boxing ?
There must be a reason, right ?
I think I see something that could be an inconsistency in the policy.
But of course, I believe the Java folks had something in mind that I don't understand yet.

Ascendant
  • 827
  • 2
  • 16
  • 34

1 Answers1

0

I believe it has to do with a design decision to insure that old code continued to work with newer Java versions. Java had widening before boxing, so adding in the boxing mechanic had to be done in such a way as to not break the logic of the pre-existing code.

A slightly more thorough answer can be found here: SCJP: can't widen and then box, but you can box and then widen

Community
  • 1
  • 1
Kon
  • 10,702
  • 6
  • 41
  • 58
  • I know that, the Java compiler favors widening over boxing for backwards compatibility. It's in my post. My question is, when it has to do a two fold conversion, why does it box-then-widen ? – Ascendant Jul 10 '13 at 08:13