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

前端 未结 5 714
面向向阳花
面向向阳花 2021-01-30 07:34

How should I declare main() method in Java?

Like this:

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


        
5条回答
  •  隐瞒了意图╮
    2021-01-30 07:44

    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

提交回复
热议问题