Subsections
A program consisting of only consecutive statements is immediately useful,
but very limited. The ability to control the order in which statements are
executed adds enormous value to any program. This lesson covers all the
control flow statements that direct the order of execution, except for
exceptions.
Upon completion of this section, students will be able to:
- Define expression statements and declaration statements.
- Describe the operation of Java's control-flow statements.
- Use Java's if-else, switch, while, do-while, and for statements.
- Use labels, and labeled break and continue statements.
- Two basic statements - expression statements, declaration statements.
- Expression statements - such as i++ -have a semi-colon at the end.
- Assignment: those that contain =
- Prefix or postfix forms of ++ and -
- Methods calls.
- Object creation statements (new operator).
- Declare a variable and initialize it to a value.
- Can appear anywhere inside a block.
- Local variables exist only as long as the block containing their code is executing.
- Braces group zero or more statements into a block.
- Basic form of conditional control flow.
if (boolean-expression)
statement1
else
statement2
- Example
class IfElse1 {
public static void main (String[] args) {
int i = 10;
if ( i==1 )
System.out.println( "i == 1" );
else if ( i==2 )
System.out.println( "i == 2" );
else if ( i==3 )
System.out.println( "i == 3" );
else
System.out.println( "don't know what 'i' is" );
}
}
- Statements can be labeled.
- Typically used on blocks and loops.
label : statement
- Used to exit from any block (not just a switch).
- Most often used to break out of a loop.
- An unlabeled break terminates the innermost switch, for, while, or do-while.
- To terminate an outer statement, label the outer statement and use its label name in the break statement.
- Skips to the end of a loop's body and evaluates the boolean expression that controls the loop.
- Has meaning only inside loops: while, do-while, and for.
- A labeled continue will break out of any inner loops on its way to the next iteration of the named loop.
- No goto construct to transfer control to an arbitrary statement in a method.
- Primary uses of goto in other languages:
- Controlling outer loops from within nested loops. Java provides labeled break and continue.
- Skipping the rest of a block of code that is not in a loop when an answer or error is found. Use a labeled break.
- Executing cleanup code before a method or block of code exits. Use a labeled break, or the finally construct of the try statement.
|
|