The Java Tutorials' Weblog

pageicon Tuesday Oct 23, 2007

Tutorial Feedback Question - Preferred Position of Array Brackets

We received the following question this week on the tutorial feedback alias:
In some places, one comes across:
public static void main(String[] args)
while at other places it is:
public static void main(String args[])
Which is 'recommended' and why?

I know that the preferred form is String[] args, but I decided to go to the source to find out why. In this case, that would be Alex Buckley, lead of the JLS (Java Language Specification) and JVMS (Java Virtual Machine Specification). In Alex's own words:

String[] is preferred because it keeps the type of args — array of String — all together. In a more complicated and poorly formatted method signature, it could be easy to miss a [] after a parameter name.
Which is pretty much what I thought. Alex goes on to point out that the following statements are equivalent:
String[][] s;
String[]   s[];
String     s[][];
However, the middle form is a maintenance headache and is not recommended. In general, arrays cause all sorts of problems at runtime — bounds must be checked as well as the runtime type of the array:
Object[] o = new String[5];
o[0] = new Integer(1);  //Compiles OK, but gives ArrayStoreException

For these reasons and because they offer more flexible options, the Collections classes are preferred to arrays. You might want to check out our Collections tutorial, written by Josh Bloch, author of the well known book, Effective Java.

Thanks, Alex!

-- Sharon Zakhour

Comments:

I might add -

String[] a,b;

means a and b are string arrays.

String a[], b;

means a is an array but b is not.

This is one of the common mistakes done. When the [] is on the left, it belongs to type, but while on right it belongs to variable.

Posted by Viswanath on October 24, 2007 at 01:48 PM PDT #

Good point!

Posted by Sharon Zakhour on October 25, 2007 at 07:15 AM PDT #

Good Point

Posted by 59.92.23.101 on October 31, 2007 at 03:29 AM PDT #

String[] s[];

Didn't know this was legal... not pretty at all.

Posted by armandino on January 20, 2008 at 10:52 PM PST #

Very interesting. Never thought about that before...

Posted by HabsQ on April 19, 2008 at 12:12 PM PDT #

good article

Posted by burs on June 03, 2008 at 10:10 PM PDT #

thanks for your article sir.

Posted by sikiş izle on June 30, 2009 at 02:25 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed

« February 2010
SunMonTueWedThuFriSat
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
      
       
Today

Feeds

Search this blog

Links

Weblog menu

Today's referrers

Today's Page Hits: 243