Conditional Statements and Loop Control in Java

Topic Overview

Welcome! In this lesson, we're exploring special instructions in the Java language: Conditional Statements, along with the break and continue statements. As we've learned, loops allow us to execute a block of code numerous times. By combining these loops with conditional statements and incorporating the useful break and continue instructions, we achieve more robust and efficient code. Let's dive in!

The 'if' Statement

In Java, the if statement triggers actions in our code based on a specific condition. Consider this straightforward example where the if statement determines which message to print based on the value of temperature:

class Solution {
    public static void main(String[] args) {
        int temperature = 15;
        if (temperature > 20) {
            System.out.println("Wear light clothes."); // This message will print if the temperature is over 20.
        } else {
            System.out.println("Bring a jacket."); // This message will print otherwise.
        }
    }
}

We can evaluate multiple conditions using else if. This phrase means, "If the previous condition isn't true, then check this one":

class Solution {
    public static void main(String[] args) {
        int temperature = 15;

        if (temperature > 30) {
            System.out.println("It's hot outside!"); // This will print if the temperature is over 30.
        } else if (temperature > 20) {
            System.out.println("The weather is nice."); // This will print if the temperature is between 21 and 30.
        } else {
            System.out.println("It might be cold outside."); // This will print if the temperature is 20 or below.
        }
    }
}

The 'break' Statement

We use the break statement whenever we want to exit a loop prematurely once a condition is met:

import java.util.ArrayList;
import java.util.Arrays;

class Solution {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 3, 7, 9, 12, 15));

        for (int i = 0; i < numbers.size(); i++) {
            if (numbers.get(i) % 2 == 0) {
                System.out.println("The first even number is: " + numbers.get(i)); // This prints the first even number.
                break; // This stops the loop after printing the first even number.
            }
            System.out.println("Number: " + numbers.get(i));
        }
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal