Skip to content

Java Conditions and Loops

Conditional statements and loop statements are core structures in programming used to control the flow of program execution. Conditional statements allow programs to execute different code paths based on specific conditions, while loop statements allow programs to repeatedly execute a block of code until a certain termination condition is met.

Conditional Statements

1. if Statement

The if statement is the most basic conditional control structure. If the conditional expression inside the parentheses evaluates to true, the subsequent code block is executed.

java
int score = 95;
if (score >= 60) {
    System.out.println("Passed!");
}

2. if-else Statement

The if-else statement executes one code block when the if condition is true, and another code block when the condition is false.

java
int temperature = 15;
if (temperature > 25) {
    System.out.println("Hot weather, wear short sleeves.");
} else {
    System.out.println("Cool weather, wear a jacket.");
}

3. if-else if-else Statement

When multiple conditions need to be evaluated, this structure can be used. It checks each condition in order, and once a condition evaluates to true, it executes the corresponding code block and then exits the entire structure.

java
int score = 85;
if (score >= 90) {
    System.out.println("Excellent");
} else if (score >= 80) {
    System.out.println("Good"); // This code will be executed
} else if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

4. switch Statement

The switch statement is suitable for evaluating a variable against multiple possible values. Starting from Java 14, switch introduced more concise "arrow" syntax and expression form.

Traditional switch (requires break)

java
int day = 3;
String dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Unknown";
        break;
}
System.out.println(dayName); // Output: Wednesday

Modern switch Expression (JDK 14+)

This new syntax is more concise, doesn't require break, and can return a value as an expression.

java
int day = 3;
String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Unknown";
};
System.out.println(dayName); // Output: Wednesday

Loop Statements

1. for Loop

The for loop is ideal when the number of iterations is known in advance. It consists of three parts: initialization, loop condition, and iteration statement.

java
// Print numbers from 0 to 4
for (int i = 0; i < 5; i++) {
    System.out.println("Current number is: " + i);
}

2. Enhanced for Loop (For-Each Loop)

The enhanced for loop is used to iterate over all elements in an array or collection. The syntax is more concise and less error-prone.

java
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
    System.out.println(number);
}

3. while Loop

The while loop checks the condition before the loop body executes. As long as the condition is true, the loop continues. It's suitable for scenarios where the number of iterations is uncertain.

java
int count = 0;
while (count < 5) {
    System.out.println("Count is: " + count);
    count++;
}

4. do-while Loop

The do-while loop is similar to the while loop, but it executes at least once because the condition check happens after the loop body executes.

java
int i = 10;
do {
    System.out.println("Value of i is: " + i); // This line will execute once
    i++;
} while (i < 5);

Loop Control Statements

  • break: Immediately terminates and exits the entire current loop.

    java
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            break; // When i equals 5, the loop ends
        }
        System.out.println(i);
    }
    // Output 0, 1, 2, 3, 4
  • continue: Skips the remaining part of the current iteration and proceeds directly to the next iteration.

    java
    for (int i = 0; i < 5; i++) {
        if (i == 2) {
            continue; // When i equals 2, skip this print
        }
        System.out.println(i);
    }
    // Output 0, 1, 3, 4

Content is for learning and research only.