Journey to Java: Episode 5 “Control Flow”

Adam Adolfo
2 min readMar 29, 2021

Control Flow in programming is defined as the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. When writing our programs we want to be able to adjust the flow of the program based on conditions we set to avoid the code to be executed top to bottom.

In previous blogs in this series we talked about if else statements and conditionals. There are more powerful and helpful statements we can use to control flow in Java. We will be using the switch statement, the for statement, the while, statement, and the do-while statement.

Switch

Using the if then statement is fine with a simple example but if we need to have many else ifs inside our if else statement the code can get repetitive and hard to read. This is where the switch statement comes in.

int value = 1;switch(value) {
case 1:
System,out.println("value was 1");
break;
}

In this example we have a switch that takes in the variable. We then will use the case keyword to check a condition. If the condition is met we will run the following line of code until you hit the break keyword. Break will terminate the switch and continue the flow of code after the switch block. The equivalent to the else keyword to handle all other cases will be the default keyword.

For

For statement or for loop is used to loop a certain amount of times. This executes a block a certain amount of times until a condition is met.

for(init; termination; increment) {}

Init is a value that is code that is initialized once at the beginning of the loop. Termination is how we want to exit by evaluating false. Increment is invoked each time the loop is run.

for(int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}

While

A for loop executes a set amount of times. A while loop executes until a condition evaluates to false. This is good when you don’t know how many times you will have to loop.

int count = 0;
while(count != 5) {
System.out.println("count is " + count);
count++;
}

Do While

The do while loop is useful because it will always execute the loop at least once or more times depending on how the condition is set. This can cause an infinite loop if not using break keyword.

int count = 0;
do {
System.out.println(count);
count++;
} while (count != 5);

--

--