I used this code. I am confused why this int array is not converted to an object vararg argument:
class MyClass {
static void print(Object... obj) {
System.out.println("Object…: " + obj[0]);
}
public static void main(String[] args) {
int[] array = new int[] {9, 1, 1};
print(array);
System.out.println(array instanceof Object);
}
}
I expected the output:
Object…: 9
true
but it gives:
Object…: [I@140e19d
true
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[]
.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With