new

Create new object

Bytecode

Type Description
u1 new opcode = 0xBB (187)
u2 index

Stack ... ==> ..., objectref

Description

new is used to create object instances. new takes a single parameter, <class>, the name of the class of object you want to create. <class> is resolved into a Java class (see Chapter 7 for a discussion of how classes are resolved). Then new determines the size in bytes of instances of the given class and allocates memory for the new instance from the garbage collected heap. The fields of the instance are set to the initial value 0 (for numeric and boolean fields), or null (for reference fields). Next, a reference to the new object is pushed onto the operand stack.

Note that the new object is initialize uninitialized - before the new object can be used, one of its <init> methods must be called using invokespecial, as shown in the example below.

The unsigned index is used to get access to class entry.  The symbolic reference is resolved  and must result in a class type (it must not result in an array or interface type). Memory for a new instance of that class is allocated from the garbage-collected heap, and the instance variables of the new object are initialized to their default initial values . The objectref, a reference to the instance, is pushed onto the operand stack.

Example

; This example creates a new StringBuffer object. This is like the Java code:
;
;    StringBuffer x = new StringBuffer();

; 1. use new to create a new object reference
new java/lang/StringBuffer

; 2. dup the object reference and call its constructor
dup
invokespecial java/lang/StringBuffer/<init>()V

; 3. assign object reference on the stack to a local variable
astore_1
; local variable 1 now contains a StringBuffer object,
; ready for use


; the following example shows how to call a non-default
; constructor. It is like the Java code:
;
;    StringBuffer x = new StringBuffer(100);
new java/lang/StringBuffer
dup
bipush 100
invokespecial java/lang/StringBuffer/<init>(I)V
astore_1

Exceptions

OutOfMemoryError - not enough memory to allocate a new instance

InstantiationError - The class named by <type> is an abstract class or an interface

Note

The new instruction does not completely create a new instance; instance creation is not completed until an instance initialization method has been invoked on the uninitialized instance.