Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading with Short and int

Tags:

java

Why this code will print int?

public static void main(String[] args) {
    short s = 5;
    A(s);
}
public static void A(int a){
    System.out.println("int");
}

public static void A(Short a){
    System.out.println("short");
}
like image 269
ilalex Avatar asked Jun 07 '11 16:06

ilalex


2 Answers

Because upcasting to int was in version 1.0 of Java and auto-boxing was added in version 5.0. Changing the behaviour would break code written for older version of Java.

However, mixing types like this suggests there is something wrong with your design, its only something you are going to find in puzzlers. ;)

like image 83
Peter Lawrey Avatar answered Oct 18 '22 22:10

Peter Lawrey


Because widening beats boxing

Reason:

Because widening was there long long before where boxing was introduced later on so not to break any code it does this.

like image 12
jmj Avatar answered Oct 18 '22 22:10

jmj