anewarray

Create new array of objects

Bytecode

Type Description
u1 anewarray opcode = 0xBD (189)
u2 index

Stack ..., count ==> ..., arrayref

Description

The count must be of type int. It is popped off the operand stack. The count represents the number of components of the array to be created.

In bytecode, immediately after the anewarray opcode there is a 16-bit unsigned integer index. The item at that index in the constant pool must be a class entry, which is a symbolic reference to a class, array, or interface type. The symbolic reference is resolved.

A new array with components of that type, of length count, is allocated from the garbage-collected heap, and a reference arrayref to this new array object is pushed onto the operand stack. All components of the new array are initialized to null, the default value for reference types. A reference to the new array is pushed onto the stack. Entries in the new array are initially set to null.

Example

; Allocate a 10-element array of for holding references to
; Threads. This is like the Java code:
; Thread x[] = new Thread[10];

bipush 10
anewarray java/lang/Thread
astore_1 ; store the new array in local variable 1

; Allocate a multi-dimensional array like:
; new String[2][5]

; using anewarray. First, allocate new 2-element array for holding
; arrays of strings and store it in local variable 1.
iconst_2
anewarray [Ljava/lang/String; ; type descriptor for array-of-String
astore_1

; next, allocate first array of String[5] and store it in index 0
aload_1
iconst_0
bipush 5
anewarray java/lang/String
aastore

; finally, allocate second array of String[5] and store it in index 1
aload_1
iconst_1
bipush 5
anewarray java/lang/String
aastore

Exceptions

NegativeArraySizeException - size is less than zero

Notes The anewarray instruction is used to create a single dimension of an array of object references. It can also be used to create a part of a multidimensional array. In this case we should use array type descriptor like [Ljava/lang/String;.