Understanding Flow Control in your application is critical. Flow Control refers to the path your code will follow and execute and what will happen in what order. If statements offer your first opportunity to explore Flow Control.
Flow Control Example 1
Consider the code below:
class Main {
public static void main(String[] args){
int i = 10;
if(i > 0){
System.out.print("Lorem");
if (i > 10) {
System.out.print(" Ipsum");
} else if ( i > 5) {
System.out.print(" Dolor");
}
System.out.print(" Sit");
if (i >= 10) {
System.out.print(" Amet");
}
System.out.print(" Consectetur");
}
}
}
Analyze the Example 1
Do your best to examine the code above line by line.
- Why didn't "Ipsum" print?
- Why did "Lorem" print?
- Why did "Dolor" print?
- Why did "Sit" print?
- Why did "Amet" print?
- Why did "Consectetur" print?
The path that the code followed and the reason that "Ipsum" did not print but "Sit" is referred to as Flow Control, and it is important to understand the Flow Control for all possible conditions in your code.
Flow Control Example 2
Here is another example:
class Main {
public static void main(String[] args){
int i = 10;
if(i >= 0){
if (i > 10) {
if (i > 20){
System.out.println("happy bear");
} System.out.println("comfy monkey");
} System.out.println("serious sloth");
}else {
System.out.println("fast dog");
}
System.out.println("agile lizard");
}
}
Analyze the Example 2
Review the code above to see why "serious sloth" and "agile lizard" were printed, but no others were.
- Why did "serious sloth" print?
- Why did "agile lizard" print?
- Why didn't anything else print?
If you can answer these questions, you understand Flow Control using if statements.
Summary: What is Flow Control in Java?
- Flow control is the path that your code will follow and execute
- One way this flow is changed is through conditional statements like
if - It is vital to understand what happens in your code for all possible conditions