Performance Zone is brought to you in partnership with:

Peter is a DZone MVB and is not an employee of DZone and has posted 162 posts at DZone. You can read more from them at their website. View Full User Profile

Java Arrays, Wat!?

  • submit to reddit

There are a few things you can do with arrays which are surprising.

Is it an array or not?
Serializable array = new Serializable[9];

Is array an array or a scalar? Well its a scalar which points to an array. Just like 

Object o = new Object[9];

You can assign an array to an object because it is also an object.  However, arrays are also Serializable so you can assign them to Serializable.

Where did my [] go?The [] can appear in surprising places.  This compiles for backward comparability reasons.
public static int method(int[]... args)[] {
    return args[0];
And the types here are; args is an int[][] and the return type is int[].  Did you notice the [] after the method declaration!  This is not part of the JLS and the OpenJDK allows this due to backward compatibility reasons.What is the difference between int[] array and int array[] ?There is a difference in what comes after it.
int[] array, x[];
int array[], y[];
In these cases; x is an int[][] but y is only an int[].
What happens if an array initialization is too large?Say I initialize an array like this
public static final int[] VALUES = {
            /* many, many lines deleted */
The errors message is;
Error:(6, 31) java: code too large
This seems a little strange.  It doesn't complain the array is too large.  In fact if I have more static fields or use larger constants, it will fail for a smaller array.
This happens because arrays are initialised in byte code.  There byte code creates the array and initialises each value, one at a time.  This results in a lot of code for large arrays which would be such a problem if there wasn't a limit in the size of a method. i.e. 65535 bytes.  The compiler generates one and only one method for a constructor or static initialization so this limits how many enums you can have and how large your initialised arrays can be.
Published at DZone with permission of Peter Lawrey, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)