vcmkrtchyan
vcmkrtchyan

Reputation: 2626

How java casts parameters to pass to a method?

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

Answers (3)

Ninad
Ninad

Reputation: 21

Note these rules:

  1. You CANNOT widen and then box. (An int can't become a Long.)
  2. You CANNOT widen from one wrapper type to another. (IS-A fails.)
  3. You can box and then widen. (An int can become an Object, via Integer.)

Upvotes: 2

Silver Fox
Silver Fox

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

Artur Vahanyan
Artur Vahanyan

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

Related Questions