What is the difference between String[] and String... in Java?

Edward Ruchevits picture Edward Ruchevits · Aug 15, 2012 · Viewed 76.2k times · Source

How should I declare main() method in Java?

Like this:

public static void main(String[] args)
{
    System.out.println("foo");
}

Or like this:

public static void main(String... args)
{
    System.out.println("bar");
}

What's actually the difference between String[] and String... if any?

Answer

davidbuzatto picture davidbuzatto · Aug 15, 2012

How should I declare main() method in Java?

String[] and String... are the same thing internally, i. e., an array of Strings. The difference is that when you use a varargs parameter (String...) you can call the method like:

public void myMethod( String... foo ) {
    // do something
    // foo is an array (String[]) internally
    System.out.println( foo[0] );
}

myMethod( "a", "b", "c" );

// OR
myMethod( new String[]{ "a", "b", "c" } );

// OR without passing any args
myMethod();

And when you declare the parameter as a String array you MUST call this way:

public void myMethod( String[] foo ) {
    // do something
    System.out.println( foo[0] );
}

// compilation error!!!
myMethod( "a", "b", "c" );

// compilation error too!!!
myMethod();

// now, just this works
myMethod( new String[]{ "a", "b", "c" } );

What's actually the difference between String[] and String... if any?

The convention is to use String[] as the main method parameter, but using String... works too, since when you use varargs you can call the method in the same way you call a method with an array as parameter and the parameter itself will be an array inside the method body.

One important thing is that when you use a vararg, it needs to be the last parameter of the method and you can only have one vararg parameter.

You can read more about varargs here: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html