Skip to content

Control Flows

In programming, executing a specific code section is often desirable based on a condition known only during the program execution. Java offers control flow statements to address such programming requirements. It enables us to create a program that can make a decision.

We will cover the following different types of control flow statements:

  • if statement
  • if-else statement
  • Nested if-else statements
  • Chaining if-else statement
  • switch statement



if statement

The if statement is the simplest decision-making statement. It is used to decide whether a block of code will be executed or not based on the condition result.

Syntax
1
2
3
4
if ( condition ) {
    // Code here gets executed when the (condition) 
    // results in true boolean value
}

Note that the condition can be any of the following that results in a single boolean value:

condition Example
boolean data values true    false
relational operators 10 >= 20 ,    3 < 90
logical operators true && false,    true ll false,   !false
boolean expression !(10 >= 20 ll 3 < 90)

Suppose the condition results in true boolean value, the code below the if statement will be executed. However, if the condition results in a false value, then the entire if statement code will be ignored.

Sample Code
// Get a random number from -10 up to 10.
int number = (int) (Math.random()*21 - 10);
System.out.println("The number is " + number);

// is it positive?
if (number > 0) {
    System.out.println(number + " is positive!");
}
// is it 0?
if (number == 0) {
    System.out.println(number + " is zero!");
}
Type & Run the Sample Code 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link

One of the common syntax error with if-statement is placing the ; right after the condition.

Subtle Mistake

The semicolon ; separates the condition with its code block { } and makes them isolated code segments. As you can see from the above example, "Hello" gets printed out regardless of false condition.

Code Sample
1
2
3
4
5
int num = 450;

if (num < -5);{
    System.out.println("Hello");
}



if-else statement

The if-else statement is helpful when we want to have two choices where only one of them will be executed based on the result of a condition.

Syntax
1
2
3
4
5
6
7
if ( condition ) {
    // this block of code will only execute 
    // when the condition results in [true] boolean value
}else{
    // this block of code will only execute 
    // when the condition results in [false] boolean value
}

The if-else statement executes if code block when condition is true.   If the condition is false, the else code block will be executed.

In the following sample code, we have a condition homeworkDone && roomCleaned which evaluates to true.   Hence, code inside the body of if-block is executed.

Sample Code
boolean homeworkDone = true;
boolean roomCleaned = true;

if(homeworkDone && roomCleaned) {
    // if-block
    System.out.println("You can hangout!");
}else{
    // else-block
    System.out.println("You cannot hangout!");
}

// --OUTPUT---
// You can hangout!
Type & Run the Sample Codes 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link



› Nested if-else statements

It is also possible to have if or if-else statements inside another if-else statement. It's called a nested statements. It is equivalent to having options inside an option. Remember that inside any code block marked by { and }, you can create any number of if or if-else statements.

Sample Code
int score = 79;

if( score < 75) {

    System.out.println("Low grade detected.");

    // nested if-else statement
    if(score >= 65) {
        System.out.println("Grade is  C");
    }
    else{
        System.out.println("Grade is  D");
    }

}else{
    System.out.println("Excellent grade detected.");

    // nested if-else statement
    // inside of else block
    if( score >= 85) {
        System.out.println("Grade is A");
    }
    else {
        System.out.println("Grade is B");
    }
}

// === OUTPUT ==== //
Excellent grade detected.
Grade is B

Even though a nested if-else statement seems intimidating, if you follow the execution flow from top to down fashion, it is surprisingly easy to understand.



› Chained if-else statement

It is if-else statements chained together with multiple conditions. Each condition gets evaluated from top to bottom until one of them is true. As soon as one of the conditions evaluates to true, the corresponding block will be executed, and the rest will be ignored.

syntax
if(  condition-1  ) {
   // codes here will be executes 
   // if condition-1 is [true]
}
else if(  condition-2  ) {
   // codes here will be executes 
   // if condition-2 is [true]
}
else if (  condition-3  ) {
   // codes here will be executes 
   // if condition-3 is [true]
}
.
.   // you can have as many as 
.   // else if(  condition-n  )  part as you wish
.
.
else {
   // codes here will be executed if all the conditions are [false]
   // note that this else block is optional
}

Please see the following example execution for execution flow:

Chained if-else executions

You can use this flow diagram to understand any chained if-else statement execution flow:

flow diagram

Try this code sample on your test case:

sample code
int age = 61;

if(age < 20) {
    System.out.println("You cannot vote!");
}
else if(age >= 20 && age <=40) {
    System.out.println("You can vote!");
}
else if(age > 40 && age < 60) {
    System.out.println("You must vote, otherwise you will pay fine.");
}
else if(age >= 60 && age <= 80) {
    System.out.println("You are not required to vote");
}
else{
    System.out.println("Retired citizen cannot vote.");
}

// === OUTPUT ==== //
// You are not required to vote
Type & Run the Sample Code 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link



switch Statement

The switch statement is a straightforward replacement for the chaining if-else statement. However, it has some limitations, and it is error-prone. Therefore, I recommend you guys use a chaining if-else statement instead.

syntax
switch (variable/expression) {
    case value1:
       // statements of case1
       break;

    case value2:
       // statements of case2
       break;

       .. .. ...
       //as many [case: ~ break;] statements you wish.
       .. .. ...

    default:
       // default statements, will be executed
       // if none of the case was evaluated. 
       // similar to [else] block 
}

The expression is evaluated once and compared with the values of each case.

  • If the expression matches with value1, the code of the case value1 is executed. Similarly, the code of case value2 is executed if the expression matches with value2.
  • If there is no match, the code of the default case is executed.

Use this flow chart to understand the execution flow:

flow diagram

Try this code sample:

Sample Code
String name = "Josh";

switch (name){

    case "Anna":
        System.out.println("Hello there !!");
        System.out.println("Anna how are you!!");
        break;
    case "Ali":
        System.out.println("Hello there !!");
        System.out.println("Ali how are you!!");
        break;
    case "Josh":
        System.out.println("Hello there !!");
        System.out.println("Josh how are you!!");
        break;
    default:
        System.out.println("Hello there !!");
        System.out.println("I don't know you");

}

// === OUTPUT ==== //
//Hello there !!
//Josh how are you!!
Type & Run the Sample Code 👩‍💻

public class SampleCode{ public static void main(String[] args){ // write code here } }//end

⚡For long lines of code, please click the Edit this program in JDoodle.com link