Deciding Our Space Journey: Overview of Conditional Statements in Java

Hello again, fellow Java Astronaut! Today, we'll examine an essential programming tool: conditional statements. These statements help determine the path our program takes. Are you ready to dive into if-else, switch case, and the lean yet powerful ternary operator that influences our program's trajectory? Let's get started!

If and If-Else Structure

The structure of if and if-else blocks is the following:

if (condition) {
    // action if condition is true
}

// and

if (condition) {
    // action if condition is true
} else {
    // action if condition is false
}

So, when the provided condition is true, we enter the action in the if block, and when the condition is false, we enter an optional else block.

Exploring the Interstellar Cloud of Java If-Else Statement

An if statement is simple yet powerful, instructing the computer to perform actions only under specific conditions. Let's imagine deciding to land on a planet with breathable air:

int oxygenLevel = 78; // The level of oxygen on the planet

if (oxygenLevel > 20) {
    System.out.println("Planet has breathable air!"); // Oxygen level is suitable
} else {
    System.out.println("Oxygen level too low!"); // Oxygen level is not high enough
}
// The code prints: Planet has breathable air!

In the example above, the statement if (oxygenLevel > 20) checks if the oxygen level exceeds 20. If the condition proves true, it prints: "Planet has breathable air!". If it's false, else guides us to an alternative command, printing: "Oxygen level too low!".

Multiple conditions: Else If Statement

For multiple conditions, we rely on else if:

int oxygenLevel = 58;
if (oxygenLevel > 70) {
    System.out.println("Excellent Oxygen level!");
} else if (oxygenLevel > 50) {
    System.out.println("Oxygen level is acceptable.");
} else {
    System.out.println("Oxygen level is too low!");
}
// The code prints: Oxygen level is acceptable.

The else if keyword provides alternate paths until a suitable one is found, ensuring we react appropriately to varying oxygen levels. Once the first condition is met, the program ignores all remaining else if conditions below.

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