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 
4
  • 10
    No difference.. Commented Dec 20, 2013 at 10:07
  • 4
    The former is supported to please former C programmers. Commented Dec 20, 2013 at 10:09
  • About the first form, this says "convention discourages this form" Commented Dec 20, 2013 at 10:09
  • This question and accepted answer has some more info on the subject. Commented Dec 20, 2013 at 10:12

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.
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.

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.