// This anonymous array style can also be used in other statements. String[] days = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};You can also use anonymous array syntax in other parts of the program. For example,
// Outside a declaration you can make this assignment. x = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};You must be careful not to create these anonymous arrays in a loop or as local variables because each use of
new
will create another array.
Because arrays are allocated dynamically, the initialization
values may arbitrary expresssions. For example, this call
creates two new arrays to pass as parameters to drawPolygon
.
g.drawPolygon(new int[] {n, n+45, 188}, new int[] {y/2, y*2, y}, 3);
int[] a; // Java style -- good int a[]; // C style -- legal, but not Java style
a.length()
instead of a.length
.
The length()
method is used with Strings, not arrays.int[100] a;
instead of int[] a = new int[100];
.