Why do I get a compilation warning here (var args method call in Java)

It is because String[] and Object... do not exactly match up.

You have to cast the String[] to either Object[] (if you want to pass the Strings as separate parameters) or Object (if you want just one argument that is an array) first.

 tva.varArgsMethod((Object[])args);    // you probably want that

 tva.varArgsMethod( (Object) args);    // you probably don't want that, but who knows?

Why is this a warning and not an error? Backwards compatibility. Before the introduction of varargs, you had these methods take a Object[] and code compiled against that should still work the same way after the method has been upgraded to use varargs. The JDK standard library is full of cases like that. For example java.util.Arrays.asList(Object[]) has changed to java.util.Arrays.asList(Object...) in Java5 and all the old code that uses it should still compile and work without modifications.


The argument of type String[] should explicitly be cast to Object[] for the invocation of the varargs method varArgsMethod(Object...) from type TestVarArgs. It could alternatively be cast to Object for a varargs invocation
You can fix it by doing either one of the way If you cast the String[] to Object[] (ref:tva.varArgsMethod((Object[])args);)
OR
change the parameter of method to String[]
(ref:public void varArgsMethod(String ... paramArr))

Tags:

Java