Create new array
Bytecode
Type | Description |
u1 | newarray opcode = 0xBC (188) |
u1 | array-type (see below) |
In bytecode, the type of the array is specified by the array-type byte immediately following the newarray opcode, which has one of the following values:
Array Type | Value |
boolean | 4 |
char | 5 |
float | 6 |
double | 7 |
byte | 8 |
short | 9 |
int | 10 |
long | 11 |
Stack ..., count ==> ..., arrayref
Description newarray is used to allocate single-dimension arrays of booleans, chars, floats, doubles, bytes, shorts, ints or longs. For example, when you write the Java code:
new int[10];
this is compiled into:
bipush 10 ; push the int 10 onto the stack newarray int ; make an array of 10 ints. The new array is left on the stack
newarray pops a positive int, n, off the stack, and constructs an array for holding n elements of the type given by <type>. Initially the elements in the array are set to zero. A reference to the new array object is left on the stack.
The count must be of type int
. It is popped
off the operand stack. The count represents the number of elements in the array to
be created.
A new array whose components are of type atype, of length count, is
allocated from the garbage-collected heap. A reference
arrayref to
this new array object is pushed into the operand stack. All of the elements of the new
array are initialized to the default initial values for its type.
Example
; This is like the Java code: ; short x[] = new short[2]; iconst_2 ; push 2 onto the stack newarray short ; call newarray to make a 2-element short array astore_1 ; store the reference to the array in local variable 1
Exceptions
NegativeArraySizeException - n is less than zero.
OutOfMemoryError - insufficient memory to allocate the array.
Notes
In Sun's implementation of the Java Virtual Machine, arrays of type boolean
are stored as arrays of 8-bit values and are manipulated using the baload and bastore
instructions, instructions that also access arrays of type byte
. Other
implementations may implement packed boolean
arrays; the baload and bastore
instructions must still be used to access those arrays.
The Java boolean false is represented in the JVM by the integer 0; true is represented by the integer 1. Boolean arrays are actually treated as byte arrays and are initialized to false (0). You should use the baload and bastore instructions to load and store values in boolean arrays.