poguy wrote: » public static void go(Long n){System.out.println("Long "); } public static void go(Short n){System.out.println("Short "); } public static void go(int n){System.out.println("int "); } short y = 6; long z = 7; go(y); go(z); why would it output int Long?? instead of short long?? thank you
danclarke wrote: » That's actually nice concise code for exploring the rules for widening and boxing. If you try something along these lines: public static void go(Long n){System.out.println("Long "); } public static void go(Short n){System.out.println("Short "); } public static void go(Integer n){System.out.println("Integer "); } short y = 6; long z = 7; go(y); go(z); then you should get the output: "Short Long" because it won't widen from short to int and then box to Integer.
eMeS wrote: » So if you always use the object form as the parameters it will behave as expected?
danclarke wrote: » In this scenario, yes. There might be valid reasons why you want to treat "short" and "int" and "long" primitives the same, though - which you could achieve using: public static void go(long n){System.out.println("long "); } ... short y = 6; long z = 7; go(y); go(z); to give: "long long " The relevant rules being demonstrated here are that widening beats boxing, and that you can't widen then box. If the overloading of the function gives the choice between widening a "short" primitive to an "int" primitive, or boxing a "short" primitive to a "Short" wrapper, then the compiler will choose widening. However, you can't use: public static void go(Long n){System.out.println("Long "); } ... short y = 6; go(y); assuming that y will be widened to a "long" primitive, and then boxed into a "Long" wrapper. And if that isn't clear - well it took me ages to wrap my head around it - if you'll pardon the pun.