# Java: Arrays -- Intermediate

## Anonymous arrays

Java 2 added anonymous arrays, which allow you to create a new array of values anywhere in the program, not just in an initialization in a declaration.

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

## Dynamic allocation

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);

## C-style array declarations

Java also allows you to write the square brackets after the variable name, instead of after the type. This is how you write array declarations in C, but is not a good style for Java. C declaration syntax can get very ugly with part of the declaration before the variable, and part after. Java has a much nicer style where all type information can be written together without the use of a variable, and there are times when only the Java notation is possible to use.

       int[] a;   // Java style -- good
       int a[];   // C style -- legal, but not Java style

## Converting between arrays and Collections data structures

[TO DO]

## Common array problems

Some common array programming mistakes are:

- Forgetting that array subscripts start with zero.
- Writing `a.length()` instead of `a.length`. The `length()` method is used with Strings, not arrays.
- Declaring an array with a size. Eg, `int[100] a;` instead of `int[] a = new int[100];`.