Suppose, I have a code like this
public class HelloWorld {
public static String method1(String[] array){return ""+array.length;}
public static String method2(String... array){return ""+array.length;}
public static void main(String args[]) {
System.out.println(method1(new String[]{"test"})); //allowed
//System.out.println(method1("test")); Not allowed
System.out.println(method2(new String[]{"test"})); //allowed
System.out.println(method2("test")); //allowed
}
}
When I do javap HelloWorld:
C:\Users\athakur\JavaProjectWorkspace\HelloWorld\bin\test>javap HelloWorld
Compiled from "HelloWorld.java"
public class test.HelloWorld extends java.lang.Object{
public test.HelloWorld();
public static java.lang.String method1(java.lang.String[]);
public static java.lang.String method2(java.lang.String[]);
public static void main(java.lang.String[]);
}
So, as per the class file, the method1() and method2() take same array argument. Then why the difference is in the input they can take?
Like method1() cannot take simple String input, where as vararg can take variable String inputs as well as an array?
So as per the class file method1 and method2 take same array argument.
Yes, except there's extra metadata within the class file to indicate that the parameter for method2 is a varargs parameter. It's really just an extra bit of data on the parameter - that's all.
You can detect it with reflection using Parameter.isVarArgs.
All it means is that the compiler is willing to take a call like this:
method2("test")
and implicitly convert it into
method2(new String[] { "test" })
You don't always want that behaviour, so it has to be explicitly specified on the parameter using the varargs syntax.
I suspect you're also using a slightly old version of javap, if it's not showing you the difference between the two method declarations. On my version (Java 8) I get:
public static java.lang.String method1(java.lang.String[]);
public static java.lang.String method2(java.lang.String...);
The only difference is signature of a method that might have a variable number of arguments, as opposed to an array argument you can pass only one argument. Anyway passing array to a method as vararg is accepted and will be used internally. On the other hand vararg arguments will be converted to an array and used there.
When you pass an array as argument to both method works. To answer you question lets don't use an array
System.out.println(method2("test")); //allowed
System.out.println(method2("test","test2")); //allowed
This works only if you use vararg argument, as you have noticed.
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