tableswitch : jump according to a table : index : visitTableSwitchInsn()

Description
tableswitch is used to perform computed jump. The jump table used by tableswitch is given in the bytecode after the tableswitch opcode.

An integer, val, is popped off the top of the operand stack. If this value is less than <low>, or if it is greater than <high>, execution branches to the address (pc + default_offset), where pc is the address of the tableswitch opcode in the bytecode, and default_offset is taken from the bytecode and is the relative address of the instruction at <defaultLabel>.

If val is in the range <low> to <high>, execution branches to the i'th entry in the table, where i is (val - <low>) and the first entry in the table is index 0. i.e. pc becomes the address (pc + table[val - <low>]).

The following pseudo-code illustrates the computation performed by tableswitch:

int val = pop();                // pop an int from the stack
if (val < low || val > high) {  // if its less than <low> or greater than <high>,
    pc += default;              // branch to default 
} else {                        // otherwise
    pc += table[val - low];     // branch to entry in table
}
Notice that all addresses stored in the table are relative to the address of the tableswitch opcode in the bytecode. If you are using Jasmin, these addresses are computed for you from the address of the given labels.
Example
    iload_1 ; push local variable 1 onto the stack
    ; if the variable contains 0, jump to ZeroLabel
    ; if the variable contains 1, jump to OneLabel
    ; if the variable contains 2, jump to TwoLabel
    ; otherwis jump to DefaultLabel
    tableswitch 0 2
        ZeroLabel
        OneLabel
        TwoLabel
      default: DefaultLabel
ZeroLabel:
    ; the variable contained 0 ...
    ldc 100
    ireturn   ; return the result 100
OneLabel:
    ; the variable contained 1 ...
    bipush 200
    ireturn   ; return the result 200
TwoLabel:
    ; the variable contained 2 ...
    bipush 300
    ireturn   ; return the result 300
DefaultLabel:
    ; the variable contained something else ...
    bipush 0
    ireturn   ; return the result 0
Notes
Addresses are measured in bytes from the start of the bytecode (i.e. address 0 is the first byte in the bytecode of the currently executing method).
See also
lookupswitch
Stack
Before After
val ...
... ...
Bytecode
Type Description
u1 tableswitch opcode = 0xAA (170)
- ...0-3 bytes of padding ...
s4 default_offset
s4 <low>
s4 <low> + N - 1
s4 offset_1
s4 offset_2
... ...
s4 offset_N