public class Roshni {
void sum(int i, int j) {
System.out.println("inside 1st i = " + i);
}
void sum(short i, int j) {
System.out.println("inside 2nd i = " + i);
}
public static void main(String s[]) {
Roshni r = new Roshni();
r.sum(5, 5);
}
}
now my question is why sum(int i,int j) is being called even if the first command line parameter 5 comes under the range of short whereas while i am typecasting like this r.sum(Short(5),5); then it is calling sum(short i,int j)
This isn't a matter of overload resolution - your method with the short
parameter isn't even applicable. Here's an example:
public class Test {
public static void foo(short x) {
}
public static void main(String[] args) throws Exception {
foo(5); // Error
}
}
This gives a compile-time error:
Test.java:10: error: incompatible types: possible lossy conversion from int to short
foo(5);
^
The type of the integer literal is int
, and there's no normal implicit conversion from int
to short
. Now you can write:
short x = 5;
... because that's in an assignment context, where additional conversions are available:
In addition, if the expression is a constant expression (ยง15.28) of type
byte
,short
,char
, orint
:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.
That doesn't apply to method arguments, however.
Once you've got a value of type short
, then overload resolution would come into play:
short x = 5;
r.sum(x, 5);
Now both methods are applicable, and the compiler will pick the second one as the more specific one following the rules of JLS 15.12.2.5.
See more on this question at Stackoverflow