Sage-Code Laboratory
index<--

Java Control Flow

The control flow is a metaphor. Imagine the computer program as a river. The river flow downhill. From time to time it can form branches that split the water flow then can join back together into the main flow. Likewise the logic of a program can split and join back into the main branch. For this we use special statements that control the workflow.

Decision Statement

A decision statement allow to perform one operation or another depending on certain condition. If the condition is met then the computer will resolve the first course of action, otherwise they will perform a different course of action or will skip ahead to next statement.

decision

Conditional Execution


Syntax:

/* two branches */
if (condition){
    //true branch
    ...
}
else {
    //false branch
    ...
};

Decision Ladder

Sometimes one condition is not good enough. When we fail first condition, maybe we need further analyses of the situation or case. Then we can link together many "if" statements in a single chain. This is sometimes called ladder because the diagram looks like one.

decision ladder

Decision Ladder

Note: You can use "else if", two keywords to create a ladder. This is possible in Java due to lack of any symbol required after the "else". In Python after else you must use ":" but in Java you can use a block { ... }.

Example:

/* multi-path decision */
int age = 25;

if(age >= 21){
    System.out.println("You can legally drink alcohol.");
}
else if(age > 18){
    System.out.println("You can vote.");
}
else if(age > 13){
    System.out.println("You are considered a teenager.");
else {
    System.out.println("You are considered a child.");
};

Switch Statement

Switch statements are a more advanced way of handling decisions in code. Code that can be written using a switch can also be written using if/else conditions. Usually is preferable to use a switch when there is a variable that can have different values that can lead the execution path.

switch

Switch Diagram


Example:

/* demo switch statement */
int season= 3;
String seasonString;

switch(season){
    case 1:
        seasonString = "Spring";
        break;
    case 2:
        seasonString = "Summer";
        break;
    case 3:
        seasonString = "Autumn";
        break;
    case 4:
        seasonString = "Winter";
        break;
    default:
        seasonString = "Error, the season you have entered is invalid."
}
System.out.println(seasonString);

Repetition

The next important control flow mechanism you need to know are the repetitive statements also known as "Loops". A loop has an entry header that start with a keyword, and a block of code that is the repetitive block. There are three types of loop statements in Java each having different use-cases:

  1. while loop
  2. for loop
  3. do... while

While Loop

A while loop is the most flexible loop you can use and the most straightforward. The downside however is that while loops are difficult to master. If you don't think out how your code increments beforehand you will likely end up with an off-by one or index out of bounds error. In layman's terms they are more prone to human errors.

loop

Repetition Diagram

Example:

int eggs = 12;
int eggsThrown = 1;//part 1

while (eggsThrown < 12){//part 2
    System.out.println("The egg hits the Neighbors house.");
    eggsThrown++;//part 3
}

This code will print out that I threw 11 eggs at my neighbors house. Notice the three important parts of a loop:

  1. Initializing a number I will use to count during the execution of my loop
  2. Checking for a condition (like eggsThrown being less than 12)
  3. Changing a number (counting UP each time I egg my neighbors house)

Now imagine you had to write out these parts over and over again... It would get tedious very quickly especially if you had a career in programming. So programmers invented a more time efficient way of doing everything in one easy to write statement.

For Loop

This kind of loop is created using keyword "for" and it has two usages: One is to iterate a specific number of times over a range of numbers. Second is to iterate over a collection of items in array. This loop is using a control variable usually "i" or "j" that is incremented by 1 every iteration until it reaches the upper limit. Then the repetition will stop.

Control Expressions:

This loop has a three control expression separated by semicolons and enclosed in parenthesis (...):

  1. the init statement: executed before the first iteration
  2. the condition expression: evaluated before every iteration
  3. the post statement: executed at the end of every iteration
classic-for

Iteration Diagram

Notes: The "init" statement will often be a short variable declaration, and the variables declared by it are visible only in the scope of the repetitive block. After every iteration, the "post" statement will be executed. The loop will stop iterating once the condition evaluates to false.

Syntax:

/* for loop syntax */

for (init; condition; post) {
   // repetitive block
   ...
   continue;
   ...
   break;
}

Example:

Lets rewrite our previous example using the for-loop:

int eggs = 12;

for(int eggsThrown = 1; eggsThrown < eggs; eggsThrown++){
//notice parts 1, 2, and 3 are all on this line of code
    System.out.println("The egg hits the Neighbors house.");
}

Do While

This loop is executed once then the exit condition is verified. That is the difference. The condition is at the bottom of the execution block. We could have simulate this loop with an infinite while having condition constant "true" then we could have create a conditional break at the end of the while loop. Less elegant but totally functional.

do-while

do-while diagram


Example:

Lets rewrite our previous example by using do-while loop:

int eggs = 12;
int eggsThrown = 1;

do {
   System.out.println("The egg hits the Neighbors house.");
   eggsThrown++;
} while (eggsThrown < 12);

Branching Statements

Note:  You can interrupt the execution using break and you can "shortcut" using "continue" statement. This may help to improve the usability especially when you create nested loops.

Example

Next program demonstrate a prime number generator that uses nested loops. The inner loop has a branch. We break from the inner loop if the current analyzed "i" number is not prime. This makes the program more easy to read and shorter.

/* demonstrate break */
class Main {
  public static void main(String[] args) {
    // generate prime numbers < 30
    for (int i = 1; i < 30; i++) {
        for (int j = 2; j < i; j++) {
          if (i % j == 0) {
            break;
          };
          if (j == i-1) {
             System.out.print(i);
             System.out.print(", ");
          };
        };
    }//end for
    System.out.println("done!");
  }
}

Homework 1: This example is available on on-line for testing. open on repl.it and run it. Then modify the program to generate prime numbers < 1000.

Loop Labels

When we are dealing with nested loops, there is one more trick you can use. This is called loop with "label". A label is an identifier, (or name) given to a loop. The label is followed by column separator ":" like in the example below:

Example:

The following example program, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. We use continue out; to skip the inner loop when we found first discrepancy. We skip out from both loops using "break out" when we found first match.

/* demonstrate break and continue with label */
class Main {
    public static void main(String[] args) {

        String searchMe = "Look for a substring inside this text";
        String substring = "this";
        boolean foundIt = false;

        int max = searchMe.length() -
                  substring.length();

        // outer loop (has a label "out")
        out: for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            // inner loop (does not have a label)
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue out;
                }
            }
            foundIt = true;
                break out;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

Output:

Found it.

Homework 2: We have saved this example on-line: open on repl.it and run it. Then modify the program to search again for string "test". Do you find it?


Read next: Classes & Objects