Skip to content
On this page

Control Flow

if-else Statements:

The if-else statement is used to implement conditional branching.

java
// if-else statement
int num = 10;

if (num > 0) {
    System.out.println("Positive");
} else if (num == 0) {
    System.out.println("Zero");
} else {
    System.out.println("Negative");
}

switch Statement:

The switch statement is used to select one of many code blocks to be executed.

java
// switch statement
int dayOfWeek = 3;

switch (dayOfWeek) {
    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("Other day");
}

while Loop:

The while loop is used to execute a block of code repeatedly until a condition becomes false

.

java
// while loop
int count = 1;

while (count <= 5) {
    System.out.println("Iteration: " + count);
    count++;
}

for Loop:

The for loop is used to iterate over a sequence (e.g., array, collection, etc.).

java
// for loop
int[] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {
    System.out.println(num);
}

break and continue Statements:

The break statement is used to exit a loop prematurely, and the continue statement is used to skip the current iteration and move to the next one.

java
// break and continue statements
int[] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {
    if (num == 3) {
        break;    // Exit the loop when num is 3
    } else if (num == 2) {
        continue; // Skip the iteration when num is 2
    }
    System.out.println(num);
}