Java Flow Control

Flow control is a key part of most programming languages and Java offers several ways to do it, this web page will cover the following topics

The page is not a complete tutorial on how to use the control statements but quick look up on the syntax of the command, please refer to the Java documentation if you want a complete tutorial of the below commands.

IF statement

if (booleanExpression ) { System.out.println("Inside a IF statement ");

if ( age == 65 ) { System.out.println("Book yourself a retirement holiday");

Note: if you only have one line of code for the IF statement you can obmit the brackets but i think this makes the code not very clear (I like brackets)

IF-ELSE statement

if ( price < 100 ) {
   System.out.println("Buy it, it's a bargain");
}
else {
   System.out.println("It's to pricey wait until the sales");
}

## You can also remove the brackets when you only have one line of code for each true or false
if ( price < 100 )
   System.out.println("Buy it, it's a bargain");
else
   System.out.println("It's to pricey wait until the sales");

## Using a if-else-if
if ( price < 100 )
   System.out.println("Buy it, it's a bargin"):
else if ( price < 110 )
   System.out.println("You might be tempted");
else
   System.out.println("It's to pricey wait until the sales");

Note: always indent conditional code it makes it much more pleasant on the eyes

Ternary operator

result = ( a < b ; a ? b);

if the condition a < b is true then the value of a is assigned to result
if the condition a < b is false then the value of b is assigned to result

Note: The ternary operator (conditional operator) is a short-hand of a if-else statement

SWITCH statement

int x = 3;

switch (x) {
   case 1:
      System.out.println("x is equal to one";
      break;
   case 2:
      System.out.println("x is equal to two ";
      break;
   case 3:
      System.out.println("x is equal to three ";
      break;
   default:                                          // default block does not need to be at the end
      System.out.println("No idea what x is ?????";
}

Note: switch statements can only evaluate byte, short, int and char

WHILE statement

int x = 0;

while ( x < 10 ) {
   System.out.println("x is still less than 10");
   x++;
}

Note: it is possible that the while body may never be executed

DO-WHILE statement

int x = 0;

do {
     System.out.println("x is still less than 10");
     x++;
} while ( x < 10 );                     // notice the semi-colon

Note: The while body will always be executed once, also notice the semi-colon at the end of the while expression

FOR loop

for ( int x = 0; x < 10; x++) {
    System.out.println("x is still less than 10");
}

# More complex FOR loop
for ( int x = 0, y = 0; ( (x < 10) && (y < 10) ); x++, y++) {
    System.out.println("x and y are still less than 10");
}

Note: you can have only one logical expression but it can be very complex.

The for statement is made up of three parts

  • Control variable initialization
  • Loop continuation Condition (must evaluate to true or false)
  • Increment/Decrement of the control variable

   for ( control variable initialization ; loop continuation ; increment/decrement of the control variable )

BREAK statement

int counter = 1;

while (counter <= 10 ) {
   System.out.println ( "Counter = " + counter + " We will break on 5" );
   if ( counter == 5 )
      // Break out of the while loop
      break;
   counter++;
}

Note: The break statement when executed in a while, do/while or switch statement causes immediate exit from that structure and continues on to the next statement after the while, do/while or switch structure.

CONTINUE statement

int counter = 1;

while (counter <= 10 ) {

   if ( (counter % 2) == 0 ) {
      System.out.println ( "Counter = " + counter + " Do not print odd numbers" );
      counter++;
      continue;
   }
   counter++;
}

Note:The continue statement when executed in a while, do/while or switch skips the remaining body statements and proceeds to the next iteration of the loop.

LABELED statement

stop: // labeled compound statement
   for ( int row = 1; row <= 10; row++ ) {
      for ( int column = 1; column <= 5; column++ ) {
         if ( row == 5 )
            break stop;   // Jump to end of stop block
      }
   }

Note: Labeled break/continue statements are to breakout of nested set of structures, the beginning of the nested structure starts with a label which is a place that the break statement will exit from.

Recursion

A recursive method is a method that calls itself either directly or indirectly through another method. Every recursive method must have base case, a condition under which no recursive call is made, this prevents the recursive going into a infinite loop.

A recursive approach is taken when it is much simpler to write a recursive loop, as every recursion solution could be replaced by a iternation solution, the coding of a iternation approach can be more complex.

One final note regarding recursion is that although the code is simpler, the code will use more memory and execute slower as the overhead of calling many methods is a penalty hit.

Recursion example

public class FactorialTest {
   public static void main(String[] args) {
      for (long i = 0; i <= 10; i++) {
         System.out.println( i + " != " + factorial(i) );
      }
   }

   public static long factorial(long number)    // this method will be called many times.
   {
      if (number <= 1)
         return 1;
      else
         return number * factorial(number - 1);
   }
}