Java – nything like branch/jump table in Java


Does Java have something similar to a branch or jump table?

A branch or jump table table is, according to wikipedia,

a term used to describe an efficient method of transferring program control (branching) to another part of a program (or a different program that may have been dynamically loaded) using a table of branch instructions.

Does Java have something like this or do I just have to use if/else if/else or case statements?

Best Solution

Java has a switch statement, but whether it compiles to a jump table in bytecode is implementation-dependent. In general, compilers will build you a jump table if they find nice constants for each case in your switch statement. I'm not sure you should really care how it's implemented, though. If you're coding in Java in the first place, you're probably just fine letting the compiler and the JIT take care of these things for you.

Note that switch only works with integer primitive types and enums, so you do need to use if/else statements if you're using other object types (and you probably shouldn't be comparing doubles or floats for equality anyway).

Finally, even though enum references are technically "constant", some compilers will only generate you a jump table when you switch on enums if your switch statement is in the same compilation unit where the enum is defined. Otherwise, it will generate you an if/else chain (as you'd have to do for regular objects). For the nitty gritty details, see the forums on extending switch usage for Objects.