To create an array of a numeric type, the newarray instruction is used. Its argument is the Java type of the array you want (boolean, float, int, char, double, long, byte, or short). The length of the array is found on the stack. For example, to create an array of 99 booleans,
bipush 99 newarray boolean ; Allocate an array of 99 booleans astore_0 ; Store it in local variable 0
The result of a newarray instruction is a reference. We'll talk a lot more about how to work with references in chapter 4. For the moment, suffice it to say that you use aload and astore instructions to move them between the stack and the local variable array, just as you use iload and istore for ints. You can't use arithmetical operations on them, but you can swap them around and pop them off the stack as if they were ints or floats.
Unlike other parts of the virtual machine, the newarray instruction does distinguish between char, short, byte, boolean, and int types. This permits the JVM implementation to use a more efficient internal representation of the array.
Since boolean arrays are different from int arrays, special instructions are necessary to get information into and out of these arrays. These instructions are written as xaload, where x is the mnemonic for the type of the array (as shown in Table 3.1).
aload_0 ; Push the reference to the ; array onto the stack bipush 7 baload ; Push the array onto the stack
To set an array element in an array of ints, use the iastore instruction. First you push the array reference itself onto the stack, followed by an int that represents which element of the array you wish to set. Then push the value you wish to assign. The iastore instruction stores the value in the top slot to the array element. For example, to set array to 0,
aload_0 ; Push the array reference bipush 7 ; Push the array index iconst_0 ; Push the value we wish to set baload ; Set array to 0
Similarly, use fastore to set elements of float arrays, bastore for arrays of byte or boolean, aastore for arrays of references, etc. Table 3.10 summarizes the array operations.
To take best advantage of arrays, we must discuss control constructs. These allow you to repeat the same section of code for each element of an array, instead of having to write specific code for each element. Control constructs are important, so all of chapter 5 is devoted to them.