The Java Tutorials' Weblog
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:while at other places it is:public static void main(String[] args)Which is 'recommended' and why?public static void main(String args[])
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:
Which is pretty much what I thought. Alex goes on to point out that the following statements are equivalent:String[]is preferred because it keeps the type of args — array ofString— all together. In a more complicated and poorly formatted method signature, it could be easy to miss a[]after a parameter name.
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:String[][] s; String[] s[]; String s[][];
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
Posted at 04:55PM Oct 23, 2007 by The Java Tutorial Team | Comments[7]
Tuesday Oct 23, 2007
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 #