Java Day 4: Control Flow – Conditions

Goal of this Day

Today you will learn:

By the end, you will be able to control the flow of your programs based on conditions.

Step 1: if, else if, else

Conditions allow your program to make decisions.


int score = 85;

if(score >= 90) {
    System.out.println("A");
} else if(score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}

Explanation:

Step 2: Nested Conditions

You can place conditions inside other conditions.


int age = 20;
boolean hasTicket = true;

if (age >= 18) {
    if (hasTicket) {
        System.out.println("You may enter");
    } else {
        System.out.println("You need a ticket");
    }
}

Explanation:

Step 3: switch Statement

The switch statement is used when you have many specific cases.


int day = 3;

switch(day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Invalid day");
}

Explanation:

Practice


int score = 85;

if(score >= 90) {
    System.out.println("A");
} else if(score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}

Exercise

Create a program that assigns a grade to a student based on their score.

Steps:

Example:


public class Grade {
    public static void main(String[] args) {
        int score = 75;

        if(score >= 90) {
            System.out.println("Grade A");
        } else if(score >= 80) {
            System.out.println("Grade B");
        } else if(score >= 70) {
            System.out.println("Grade C");
        } else {
            System.out.println("Grade D");
        }
    }
}