prev next contents
anewarray

allocate new array for objects

Jasmin Syntax


   anewarray <type>

<type> is either the name of a class or interface, e.g. java/lang/String, or, to create the first dimension of a multidimensional array, <type> can be an array type descriptor, e.g. [Ljava/lang/String;

Stack

Before

After
size
arrayref
...
...
Description

anewarray allocates a new array for holding object references. It pops an int, size, off the stack and constructs a new array capable of holding size object references of the type indicated by <type>.

<type> indicates what types of object references are to be stored in the array (see aastore). It is the name of a class or an interface, or an array type descriptor. If it is java/lang/Object, for example, then any type of object reference can be stored in the array. <type> is resolved at runtime to a Java class, interface or array. See Chapter 7 for a discussion of how classes are resolved.

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

Bytecode

In bytecode, immediately after the anewarray opcode there is a 16-bit unsigned integer index. This is the index of an entry in the constant pool that is tagged a CONSTANT_Class entry. The name field of this entry is given by <type> parameter in Jasmin.

Type

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

newarray, multianewarray, new

Notes

It is more efficient to use multianewarray to allocate multi-dimensional arrays.


prev next contents
Java Virtual Machine, by Jon Meyer and Troy Downing, O'Reilly Associates