HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

7) Conditionals & Loops Lesson

Flow Control in Java

3 min to complete · By Ryan Desmond

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.

  1. Why didn't "Ipsum" print?
  2. Why did "Lorem" print?
  3. Why did "Dolor" print?
  4. Why did "Sit" print?
  5. Why did "Amet" print?
  6. 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.

  1. Why did "serious sloth" print?
  2. Why did "agile lizard" print?
  3. 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