Conditional Statements & Loops in Java

if else Statement in Java With Examples

The if-else statement allows you to execute a block of code based on a condition. If the condition is true, the if block is executed; otherwise, the else block is executed.

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

Switch Case Statement in Java With Examples

The switch statement allows you to execute one block of code among many based on the value of an expression.

switch (expression) {
    case value1:
        // code to be executed if expression equals value1
        break;
    case value2:
        // code to be executed if expression equals value2
        break;
    // you can have any number of case statements
    default:
        // code to be executed if expression doesn't match any case
}

Switch Expressions in Java 12

Switch expressions, introduced in Java 12, allow you to use the switch statement as an expression that returns a value.

int result = switch (expression) {
    case value1 -> value1Result;
    case value2 -> value2Result;
    default -> defaultValue;
};

Java for Loop With Examples

The for loop is used to iterate a part of the program several times. If the number of iterations is fixed, it is recommended to use the for loop.

for (initialization; condition; update) {
    // code to be executed
}

Java while Loop With Examples

The while loop is used to iterate a part of the program repeatedly until the specified condition is true. If the number of iterations is not fixed, it is recommended to use the while loop.

while (condition) {
    // code to be executed
}

Java do-while Loop With Examples

The do-while loop is similar to the while loop, but it checks the condition after executing the loop's body. Therefore, the loop will execute at least once.

do {
    // code to be executed
} while (condition);

break Statement in Java With Examples

The break statement is used to terminate the loop or switch statement. It breaks the current flow of the program at the specified condition.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}

continue Statement in Java With Examples

The continue statement is used to skip the current iteration of the loop and continue with the next iteration.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue;
    }
    System.out.println(i);
}

return Statement in Java With Examples

The return statement is used to exit from a method, with or without a value.

public int add(int a, int b) {
    return a + b;
}