3.10. Compiling Switches

Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices. For instance:

int chooseNear(int i) {    switch (i) {        case 0:  return  0;        case 1:  return  1;        case 2:  return  2;        default: return -1;    }}

compiles to:

Method int chooseNear(int)0   iload_1             // Push local variable 1 (argument i)1   tableswitch 0 to 2: // Valid indices are 0 through 2      0: 28             // If i is 0, continue at 28 ...

Get The Java® Virtual Machine Specification, Java SE 7 Edition, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.