The Conversion Diversion applet, included below, demonstrates a Java virtual machine executing a sequence of bytecodes that performs type conversion. This applet accompanies Chapter 11, "Type Conversion," of Inside the Java 2 Virtual Machine. The bytecode sequence in the simulation was generated by // On CD-ROM in file opcodes/ex1/Diversion.java class Diversion { static void Convert() { byte imByte = 0; int imInt = 125; for (;;) { ++imInt; imByte = (byte) imInt; imInt *= -1; imByte = (byte) imInt; imInt *= -1; } } } The bytecodes generated by 0 iconst_0 // Push int constant 0. 1 istore_0 // Pop to local variable 0, which is // imByte: byte imByte = 0; 2 bipush 125 // Expand byte constant 125 to int and push. 4 istore_1 // Pop to local variable 1, which // is imInt: int imInt = 125; 5 iinc 1 1 // Increment local variable 1 (imInt) by 1: ++imInt; 8 iload_1 // Push local variable 1 (imInt). 9 i2b // Truncate and sign extend top of stack so it // has a valid byte value. 10 istore_0 // Pop to local variable 0 (imByte): // imByte = (byte) imInt; 11 iload_1 // Push local variable 1 (imInt) again. 12 iconst_m1 // Push integer -1. 13 imul // Pop top two ints, multiply, push result. 14 istore_1 // Pop result of multiply to local variable 1 (imInt): // imInt *= -1; 15 iload_1 // Push local variable 1 (imInt). 16 i2b // Truncate and sign extend top of stack so it has // a valid byte value. 17 istore_0 // Pop to local variable 0 (imByte): // imByte = (byte) imInt; 18 iload_1 // Push local variable 1 (imInt) again. 19 iconst_m1 // Push integer -1. 20 imul // Pop top two ints, multiply, push result. 21 istore_1 // Pop result of multiply to local variable 1 (imInt): // imInt *= -1; 22 goto 5 // Jump back to the iinc instruction: for (;;) {} The The maximum value for a The Java virtual machine converts an The simulation applet shows what happens when an To drive the Conversion Diversion simulation, use the Step, Reset, Run, and Stop buttons. Each time you press the Step button, the simulator will execute the instruction pointed to by the pc register. If you press the Run button, the simulation will continue with no further coaxing on your part until you press the Stop button. To start the simulation over, press the Reset button. For each step of the simulation, a panel at the bottom of the applet contains an explanation of what the next instruction will do. Happy clicking. Click here to view a page of links to the source code of the Conversion Diversion applet. |
Copyright © 1996-1999 Bill Venners. All Rights Reserved. |