prev next contents
new

create an object

Jasmin Syntax


    new <class>
<class> is the name of the class to use, e.g. java/lang/String.

Stack

Before

After
...
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.

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

Bytecode

In bytecode, after the new opcode is a 16-bit unsigned integer index. This integer is the index of an entry in the constant pool of the current class. The entry is tagged a CONSTANT_Class entry (see Chapter 4). The name field of the entry is a string given by the <type> parameter in Jasmin.

Type

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

anewarray, newarray, multianewarray


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