Assembly Language for Beginners

(nextflipdebug2) #1

4.1. JAVA


10: ldc #5 // String int: %d double: %f.%n
12: iconst_2
13: anewarray #6 // class java/lang/Object
16: dup
17: iconst_0
18: iload_1
19: invokestatic #7 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
22: aastore
23: dup
24: iconst_1
25: dload_2
26: invokestatic #8 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
29: aastore
30: invokevirtual #9 // Method java/io/PrintStream.format:(Ljava/lang/String;[⤦
ÇLjava/lang/Object;)Ljava/io/PrintStream;
33: pop
34: return

So values of theintanddoubletypes are first promoted toIntegerandDoubleobjects using thevalueOf
methods.


Theformat()method needs objects of typeObjectat input, and since theIntegerandDoubleclasses
are derived from the rootObjectclass, they suitable for elements in the input array.


On the other hand, an array is always homogeneous, i.e., it can’t hold elements of different types, which
makes it impossible to pushintanddoublevalues in it.


An array ofObjectobjects is created at offset 13, anIntegerobject is added to the array at offset 22,
and aDoubleobject is added to the array at offset 29.


The penultimatepopinstruction discards the element atTOS, so whenreturnis executed, the stack
becomes empty (or balanced).


Two-dimensional arrays


Two-dimensional arrays in Java are just one-dimensional arrays ofreferencesto another one-dimensional
arrays.


Let’s create a two-dimensional array:


public static void main(String[] args)
{
int[][] a = new int[5][10];
a[1][2]=3;
}

public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=3, locals=2, args_size=1
0: iconst_5
1: bipush 10
3: multianewarray #2, 2 // class "[[I"
7: astore_1
8: aload_1
9: iconst_1
10: aaload
11: iconst_2
12: iconst_3
13: iastore
14: return

It’s created using themultianewarrayinstruction: the object’s type and dimensionality are passed as
operands.


The array’s size (10*5) is left in stack (using the instructionsiconst_5andbipush).


Areferenceto row #1 is loaded at offset 10 (iconst_1andaaload).


The column is chosen usingiconst_2at offset 11.

Free download pdf