6

I have seen two different ways of declaring array of String but I don't undrestand the difference. Can anyone explain what is the difference between

String args[]

and

String[] args 
  • 10
    No difference.. – vallentin Dec 20 '13 at 10:07
  • 4
    The former is supported to please former C programmers. – jpvee Dec 20 '13 at 10:09
  • About the first form, [this](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) says "convention discourages this form" – harold Dec 20 '13 at 10:09
  • [This](http://stackoverflow.com/questions/13175193/java-array-convention-string-args-vs-string-args) question and accepted answer has some more info on the subject. – Pieter Dec 20 '13 at 10:12

5 Answers5

9

There is no difference (in Java). They're exactly the same thing. From JLS §10.2:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

They is no difference but I prefer the brackets after type - it's easier to see that the variable's type is array and also it's more readable.

But always it depends on developer which approach he'll pick up and it's more comfortable for him to use. See @T.J. Crowder answer that refers to official docs.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • 1
    I prefer to follow the Java Coding Conventions, just because they are standard and saves lots of discussion about the various alternatives like space vs tabs etc. – Peter Lawrey Dec 20 '13 at 10:12
1

The only difference is if you are declaring a variable and you add more fields.

String args[], array[];  // array is String[]

String[] args, array[];  // array is String[][]

However, if you refering to your main method I prefer to use

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

or if the args are ignored

public static void main(String... ignored) {

The String... is much the same as String[] except it can be called with varargs instead of an array. e.g.

MyClass.main("Hello", "World");

BTW A good example of why I don't like [] after the variable as the type is String[] not String .... ??

This actually compiles

public int method(String args[])[] {

which is the same as

public int[] method(String[] args) {

but I think the later is better.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

There is no difference in String args[] and String[] args.Both ways are same.

rachana
  • 3,344
  • 7
  • 30
  • 49
0

there is no difference between them. They are both the declaration of an array. To Java compiler, they are same. Just declare an array variable

Longwayto
  • 396
  • 2
  • 6