Java array convention: String[] args vs. String args[]

旧时模样 提交于 2019-11-28 06:52:27

This is not from Oracle but I think it will help.

It is from Kathy Sierra's book SCJP Sun Certified Programmer for Java 6

int[] key;
int key [];

When declaring an array reference, you should always put the array brackets immediately after the declared type, rather than after the identifier (variable name). That way, anyone reading the code can easily tell that, for example, key is a reference to an int array object, and not an int primitive.

Oracle's Code Conventions do not explicitly state it, but in all examples they use the brackets immediately after the declared type.

In their example code (which should be considered authoritative in this context) they use:

private Object[] instanceVar3;

Also on the page detailing the initialization of variables they have this example that demonstrates the possible problems of putting the brackets behind the variable name:

int foo, fooarray[]; //WRONG!

One could be tempted to do this and think one were declaring several arrays. Althoug this syntactically correct (as brimborium pointed out in the comments), Oracle didn't put the capital letters there for nothing. Better to be safe, clear and also type less by putting the brackets behind the type to show clearly what you want to declare.

There is one obscure use case for the late brackets:

int x, xs[], xxs[][];

How much this is useful, I let the reader be the judge.

One advantage of using [] immediately after array type is: If you want to declare multiple arrays then you to write like: int[] a,b,c; But if you use [] after the array name, then we have to use[] after every array variable like: int a[],b[],c[];

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!