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

java

Solution

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.

Problem

Source: ``` public class TestVarArgs { public void varArgsMethod(Object ... arr) { System.out.println(arr.getClass().getName()); for(Object o : arr) { System.out.println(o); } } public static void main(String[] args) { TestVarArgs tva = new TestVarArgs(); tva.varArgsMethod(args); } } ``` Compile: ``` javac TestVarArgs.java ``` Error: ``` TestVarArgs.java:15: warning: non-varargs call of varargs method with inexact argument type for last parameter; cast to java.lang.Object for a varargs call cast to java.lang.Object[] for a non-varargs call and to suppress this warning tva.varArgsMethod(args); ^ 1 warning ``` I am using `javac 1.6.0_20` and the code o/p indicates that a non var arg call was made anyways.

Original source