What is the correct Java main() method parameters syntax?

前端 未结 9 1279
旧巷少年郎
旧巷少年郎 2020-12-06 07:56

Is there a functional difference between these methods?

public static void main(String[] args) { }

public static void main(String args[]) { }
相关标签:
9条回答
  • 2020-12-06 08:27

    There is no difference, but the first one is according to standard.

    0 讨论(0)
  • 2020-12-06 08:36

    There is not a difference between the 2 choices you can do either one of them.

    You could also put this:

    public static void main(String... args) { }
    
    0 讨论(0)
  • 2020-12-06 08:39

    Different Array notations

    The notation

    String args[]
    

    is just a convenience for C programmers, but it's identical to this notation:

    String[] args
    

    Here's what the Sun Java Tutorial says:

    You can also place the square brackets after the array's name:

    float anArrayOfFloats[]; // this form is discouraged

    However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

    Reference: Java Tutorial > Arrays

    VarArgs

    BTW, a lesser known fact is that main methods also support varargs, so this is also okay:

    public static void main(String ... args) { }
    

    The reason is that a varargs method is internally identical to a method that supports a single array parameter of the specified type.E.g. this won't compile:

    public static void main(final String... parameters){}
    public static void main(final String[] parameters){}
    // compiler error: Duplicate method main(String[])
    

    Reference: Java Tutorial > Arbitrary Number of Arguments

    0 讨论(0)
  • 2020-12-06 08:40

    I also prefer to mark the args as final.

    public static void main(final String[] args) { }
    
    0 讨论(0)
  • 2020-12-06 08:47

    No, but the first is the prefered style.

    Edit: Another option is

    public static void main(String... args)
    

    which additionally allows callers to use varargs syntax.

    0 讨论(0)
  • 2020-12-06 08:47

    Use String[] instead of use [] postfix to reference. Infact String[] obj; hilights the fact that obj is a reference of type String[] (array of String).

    0 讨论(0)
提交回复
热议问题