Why is this int array not passed as an object vararg array?

You're running into an edge case where objects and primitives don't work as expected. The problem is that the actual code ends up expecting static void print(Object[]), but int[] cannot be cast to Object[]. However it can be cast to Object, resulting in the following executed code: print(new int[][]{array}).

You get the behavior you expect by using an object-based array like Integer[] instead of int[].


As you know, when we use varargs, we can pass one or more arguments separating by comma. In fact it is a simplification of array and the Java compiler considers it as an array of specified type.

Oracle documentation told us that an array of objects or primitives is an object too:

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

So when you pass an int[] to the print(Object... obj) method, you are passing an object as the first element of varargs, then System.out.println("Object…: " + obj[0]); prints its reference address (default toString() method of an object).


The reason for this is that an int array cannot be casted to an Object array implicitly. So you actually end up passing the int array as the first element of the Object array.

You could get the expected output without changing your main method and without changing the parameters if you do it like this:

static void print(Object... obj) {
    System.out.println("Object…: " + ((int[]) obj[0])[0]);
}

Output:

Object…: 9
true

Tags:

Java