Reputation: 2626
I was reading a java book, and came up with this example
public class Main {
public static void main(String[] args) {
play(4); // DOES NOT COMPILE
play(4L);
glide(1,4); // THIS ONE COMPILES
}
public static void play(Long l) { }
public static void play(Long... l) { }
public static void glide(long i, long j) {}
}
but didn't quite get the idea why doesn't java cast the int to long and call the first method, because it does the cast for the method with 2 parameters?
Upvotes: 1
Views: 67
Reputation: 21
Note these rules:
Upvotes: 2
Reputation: 21
The third method, glide, is an example of a widening cast from an int to a long which is done automatically.
The first method, play(Long l), accepts a Long (capital L) object. Primitives cannot be cast to objects which is why your first example doesn't compile, but the compiler will convert a primitive to its equivalent object via "autoboxing" which is why play (4L) works.
Upvotes: 2
Reputation: 38
Because the method glide
uses parameters of type long
, and java easily casts int
to long
, but the first method uses parameter of type Long
, which is the wrapper class for long
type, not int
, that's why the first method doesn't compile
Upvotes: 2