Skip to main content

Control Flow

If-Else Statement

Introduction

So far, we've been writing programs that follow one instruction after another in a sequence. But in many cases, we might need to skip certain instructions and execute others to solve a problem, this is where we required control flow statements.

A real life example of the control flow use case of "decision-making" could be:

"If the traffic light is green, keep moving ;if yellow, then wait; if red, then stop".

The program flow will be something like this:

If the traffic light is green, then we should keep moving, and the "Keep moving" message is shown. If the traffic light is yellow, then we should wait, and the "Wait" message is displayed and If the traffic light is red, then we should stop, and the "Stop" message is shown.

In summary, we use these boolean expressions, like "==" etc., to make decisions in our programs. They help us choose between different sets of instructions based on whether a condition is true or false.

if Statement

Let's begin with the basic, the 'if' statement. Its syntax is as follows:

if (condition) {
// code to be executed if the condition is true
}

Here's how it functions:

The 'if' statement checks if a certain condition is either true or false.

If the condition is true, the code inside the 'if' block is executed.
If the condition is false, the code inside the 'if' block is not executed.
The curly braces indicate the body of an if statement. if the condition  is true, both statements inside the curly braces will be executed and if false, both will be skipped.

Let's try to understand it with the help of an example where we check whether a student is passed or failed in the examination.

Assuming score 40 is the passing score

import java.util.Scanner;
 
class Main {
 
    public static void main(String[] args) {
 
        Scanner input = new Scanner(System.in);
        // get student score from the user
        System.out.println("Enter score");
        int studentScore = input.nextInt();
 
        // if studentGrade is 40 or above, it means studentScore >= 40 results to true
        if (studentScore >= 40) {
            System.out.println("Yayyyy!");
            System.out.println("Congrats, You passed the examination.");
        }
    }
}

Sample output1

Enter score
50
Yayyyy!
Congrats, You passed the examination.

Explanation- Here, the user entered 50studentScore >= 40 in the if statement will be true. In this case, the statements inside the if statements are executed.

Multiple if statements

The below code example is similar to the previous one, but we have added another condition, studentScore < 50, to show different messages if the student failed the exam.

import java.util.Scanner;
 
class Main {
 
    public static void main(String[] args) {
 
        Scanner input = new Scanner(System.in);
        // get student score from the user
        System.out.println("Enter score");
        int studentScore = input.nextInt();
 
        // if studentGrade is 40 or above, that means studentScore >= 40 results to true and code inside if block will get execute.
        if (studentScore >= 40) {
            System.out.println("Yayyyy!");
            System.out.println("Congrats, You passed the examination.");
        }
        
       // if studentGrade is below 40, that means studentScore < 40 results to true and code inside the below if block will get execute.
        if (studentScore < 40) {
            System.out.println("Better luck next time, You failed the examination.");
        }   
    }
}

Sample Output1

Enter score
45
Yayyyy!
Congrats, You passed the examination.

Sample Output2

Enter score
39
Better luck next time, You failed the examination.

Instead of writing two if statements to solve the problem, we can solve it by adding else statement here which is better and easier approach. So now, we will learn how can we else statement next.

Else Statement

The if statement can have an  else clause. Its syntax is as follows:

if (condition){
    // code to be executed if the condition is true
}
else {
    // code to be executed if the condition is false
}

Explanation- Here's how the code works:

If the condition is true

  • code inside if are executed
  • code inside else are skipped

If condition is false

  • code inside else are executed
  • code inside if are skipped

Let's try to solve our previous program where we were determining whether the student is passed or failed, using if/else condition.

import java.util.Scanner;
 
class Main {
 
    public static void main(String[] args) {
 
        Scanner input = new Scanner(System.in);
        // get user input.
        System.out.println("Enter score");
        int studentScore = input.nextInt();
 
        // if studentScore is 40 or above, that means studentScore >= 40 results to true and code inside if block will get execute.
        if (studentScore >= 40) {
            System.out.println("Yayyyy!");
            System.out.println("Congrats, You passed the examination.");
        }
        // else studentScore is less than 40 and the below code will get execute. 
        else{
            System.out.println("Better luck next time, You failed the examination.");
        }   
    }
}

Sample Output

Enter score
39
Better luck next time, You failed the examination.

Explanation - Since the score < 40, the else body code is executed.

Note: The code after the if/else part will execute anyway.

Else if statement

Above we have seen how can we use if and else code to choose between the two conditions. Let's say if we have to choose among more than 2 conditions, in that case we can use else if clause. It's syntax is as follows -

if (condtion1) {
   // code to be executed if the condition1 is true
}

else if (condition2) {
  // code to be executed if the condition2 is true
}

else {
    // code to be executed if both condition1 and condition2 is false
}

Explanation- Here's how the code works:

If the condition1 is true

  • code inside if are executed
  • code inside else if are skipped
  • code inside else are skipped

If condition2 is true

  • code inside else if are executed
  • code inside if are skipped
  • code inside else are skipped

If the condition1 and condition2 are false

  • code inside else are executed
  • code inside if are skipped
  • code inside else if are skipped

Let's try to solve our previous program with some additional condition checks, using if/else if/else condition.

import java.util.Scanner;
 
class Main {
 
    public static void main(String[] args) {
 
        Scanner input = new Scanner(System.in);
        // get user input.
        System.out.println("Enter score");
        int studentScore = input.nextInt();
 
       
        // check invalid score
        if (studentScore > 100 || studentScore < 0) {
            System.out.println("Invalid score.");
        }
         // else if studentScore is 40 or above, that means studentScore >= 40 results to true and code inside if block will get execute.
        else if (studentScore >= 40) {
            System.out.println("Yayyyy!");
            System.out.println("Congrats, You passed the examination.");
        }
        // else studentScore is less than 40 and the below code will get execute. 
        else{
            System.out.println("Better luck next time, You failed the examination.");
        }   
    }
}

Sample output1

Enter score
-1
Invalid score.

Sample output2

Enter score 
42
Yayyyy!
Congrats, You passed the examination.

Quiz:



Practice Problem

Write a code to find out the largest and smallest number among three numbers based on user input.

Largest number Java code
import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the first number:");
        int first = input.nextInt();

        System.out.println("Please enter the second number:");
        int second = input.nextInt();

        System.out.println("Please enter the third number:");
        int third = input.nextInt();

       int largest = first;
       if (second > largest) {
         largest = second;
       }
       
       if (third > largest) {
         largest = third;
       }

       System.out.println("The largest number is " +largest);
    }
}

Smallest number Java code
import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the first number:");
        int first = input.nextInt();

        System.out.println("Please enter the second number:");
        int second = input.nextInt();

        System.out.println("Please enter the third number:");
        int third = input.nextInt();

        int smallest = first;
        if (second < smallest) {
          smallest = second;
        }
        
        if (third < smallest) {
          smallest = third;
        }
        
       System.out.printf("The smallest number is " + smallest);
    }
}

Common Issues That Beginners Faces

Let's try to understand the common issues faced by the beginners with the help of examples.

Statements between if and else

class Main {
 
    public static void main(String[] args) {
   
        int number = -1;
 
        if (number < 0) {
            System.out.println("Number is negative");
        }
    
        // error
        System.out.println("Statement between if and else");
    
        else {
            System.out.println("Number is positive");
        }
 
    }
}
 
// Output: error: 'else' without 'if'

Here, the error is caused by System.out.println("Between if and else");. It's neither in the if part nor in the else part. We can write code after if/else block but not in between.

Use conditions with else

class Main {
 
    public static void main(String[] args) {
   
        int number = -1;
 
        if (number < 0) {
            System.out.println("Number is negative");
        }
        else (number >= 0){
            System.out.println("Number is positive");
        }
 
    }
}
 
// Output: error: not a statement

Here, the error is caused by else (number >= 0){;. We cannot write conditions in else.

Else without if statement

class Main {
    public static void main(String[] args) {
        
        int number = 3;
        
        else {
            System.out.println("Number is positive");
        }
    }
}
 
// Output: error: 'else' without 'if'

Here, we haven't specified if block, we should have a if block before else block.

In this lesson, we familiarise ourselves with conditional branching.