user1494459
user1494459

Reputation:

Differentiate between String args[] and String[] args

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 

Upvotes: 6

Views: 336

Answers (5)

Simon Dorociak
Simon Dorociak

Reputation: 33495

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.

Upvotes: 2

Longwayto
Longwayto

Reputation: 396

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

Upvotes: 0

rachana
rachana

Reputation: 3414

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

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074208

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.

Upvotes: 9

Related Questions