|
|
|
Sponsored Link •
|
|
Advertisement
|
Summary
All Java programs are compiled into class files that contain bytecodes, the machine language of the Java virtual machine. This article takes a look at how control flow is handled by the Java virtual machine, including the relevant bytecodes.
Java offers all the control-flow constructs that
C++ programmers found endearing: if, if-else,
while, do-while, for, and
switch. (Java doesn't offer the goto, but
that was never endearing, not to real C++ programmers anyway.)
Decisions, decisions: keep it simple
The simplest control-flow construct Java offers is the
if statement. But in bytecodes, the if is
not so simple. When a Java program is compiled, the if
statement may be translated to a variety of opcodes. Each opcode pops one or two values from the top of the stack and does a comparison.
The opcodes that pop only one value off the top of the stack compare
that value with zero. The opcodes that pop two values off the stack
compare one of the popped values to the other popped value. If the
comparison succeeds (success is defined differently by each individual
opcode), the Java virtual machine (JVM) branches -- or jumps -- to the offset given
as an operand to the comparison opcode. In this manner, the
if statement provides many ways for you to make the Java virtual
machine decide between two alternative paths of program flow.
|
Sponsored Links
|