control

Java Control Flow (If, Else, and Switch)

Java Control Flow (If, Else, and Switch)

Control flow statements in Java allow you to control the execution of your code based on certain conditions.

If-Else Statement

public class ControlFlowExample {
    public static void main(String[] args) {
        int age = 20;

        if (age >= 18) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are a minor.");
        }
    }
}
    

This program uses an if-else statement to check if the user is an adult or a minor based on their age.

Switch Statement

public class SwitchExample {
    public static void main(String[] args) {
        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");
        }
    }
}
    

This example demonstrates the use of a switch statement to print the day of the week based on the value of day.