Control Statements

Control statements are used to control the flow of execution and branching based on changes to the state of the program. Control statements can be put into the following categories

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.

Selection
IF statement
if (booleanExpression ) { System.out.println("Inside a IF statement ");
        
if ( age == 65 ) { System.out.println("Book yourself a retirement holiday");
        
if (true)
    System.out.println("Hello ");       
    System.out.print("World!");                 // you actually don't need brackets but it can be hard to read code, this is not part of the if statement
        
if (false);                        
    System.out.println("Hello World!");         // notice the semi-colon at the end of the if statement, this terminates the if statement imediately and this line always executes
        
Note: you can nest if and if-else statements
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 (1 + 2):                                   // can even use expressions as well
    System.out.println("x is equal to three");
    break;
  default:                                        // default block does not need to be at the end or even included
    System.out.println("No idea what x is ?????");
}

Note: switch statements can only evaluate byte (Byte), short (Short), int (Integer) and char (Character), enumerated types and the String class

Note: missing break statements means that all case statements will be executed, known as fall-through 

Note: you can nest switch statements, when the compiler compiles a switch statement it will inspect each case statement and create a "jump" table that it will use for 
selecting the path of execution depending on the value of the expression. This gives it an advantage (better performance) over large if-else statement.
Iteration
WHILE statement
int x = 0;
while ( x < 10 ) {
    System.out.println("x is still less than 10");
    x++;
}

i = 100;
j = 200;
while(++i < --j);           // no body but will find the midpoint between i and j

System.out.println("Midpoint is " + i);

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 (only called once)
  • Loop continuation Condition (must evaluate to true or false)
  • Increment/Decrement of the control variable (executed after the iteration)

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

More information about loops:

  • You cannot reference a label with the continue or break statements that are not in the loop scope, a compile error occurs
  • An outer loop cannot reference the inners loop's labels, but an inner loop can reference the outer's loop lables
  • You can break out of a nested loop from a nested loop
  • You can also completely break out of a parent loop

FOR Loop (enhanced)
init i = 0; 
for(Strings arg : args) {
  System.out.println("Argument " + (++i) + " = " + arg);
}

int nums[] = { 1, 2, 3, 4, 5};
for(int i : nums) {
    if (i == 3)               
        continue;

    System.out.println(i);
}

Note: you can also use the break, continue and return
Jump
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.

RETURN statement
int nums[] = { 1, 2, 3, 4, 5};

for(int i : nums) {
    if (i == 3)
        return;                     // once i equals 3 the for loop will be terminated

    System.out.println(i);
}
LABELLED statement

stop: // labelled 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: Labelled 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.