The flow control statements give you to conditionally execute statements, to repeatedly operate a block of statements, or to just modify the sequential flow of control.
|
|
Looping
|
while, do-while, for
The body of the while loop is run only if the expression is true, so it cannot be executed even once:
while(i < 5){...}
The body of the do-while loop is run at least once because the test expression is evaluated only after executing the loop body. Also, don't forget the ending semicolon after the while expression.
do { ... } while(i < 5);
The for loop syntax is:
for(expr1; expr2; expr3)
{
// body
}
expr1 Æ is for initialization, expr2 Æ is the conditional test, and expr3 Æ is the iteration expression. Any of these sections may be omitted and the syntax will still be legal:
for( ; ; ) {} // an endless loop
|
Decision making
|
if-else, switch-case
The if-else statement is used for decision-making -- that is, it decides which course of action have to be taken.
if (x == 5) {...} else {..}
The switch statement is also used for decision-making, based on an integer expression. The argument passed to the switch and case statements could be int, char, short, or byte. The argument passed to the case statement could be a literal or a final variable. If no case matches, the default statement (which is optional) is executed.
int i = 1;
switch(i)
{
case 0:
System.out.println("Zero");break; //if break; is omitted case 1: also executed
case 1:
System.out.println("One");break; //if break; is omitted default: also executed
default: System.out.println("Default");break;
}
|
Branching
|
break, continue, label:, return
The break statement is needed to exit from a loop or switch statement, while the continue statement is needed to skip just the current iteration and continue with the next. The return is used to return from a function based on a condition. The label statements may lead to unreadable and unmaintainable spaghetti code hence should be avoided.
|
Exception handling
|
try-catch-finally, throw
Exceptions may be used to define ordinary flow control. This is a misuse of the idea of exceptions, which are meant only for exceptional conditions and hence should be avoided.
|