Search⌘ K
AI Features

Conditional Statements

Explore how conditional statements such as if, else, else if, and switch enable dynamic control flow in Java programs. Understand syntax, block scope, modern switch expressions, and when to use each construct to handle decision-making effectively.

In real-world situations, we often make decisions based on changing conditions. For example, if it is raining, we take an umbrella; otherwise, we leave it at home. Software systems require a similar ability to choose between different execution paths. This capability is known as control flow, and it allows programs to move beyond a fixed sequence of instructions and instead respond dynamically to user input, changing data, and defined rules.

To support this kind of decision-making, Java provides several control-flow constructs.

The if statement

The most fundamental way to make a decision in Java is the if statement. It evaluates a condition (a boolean expression) that is either true or false. If the condition is true, the compiler executes the block of code attached to it. If it is false, the compiler skips that block entirely.

A single condition controls whether a block of code runs or is skipped entirely
A single condition controls whether a block of code runs or is skipped entirely

We define the condition inside parentheses () immediately after the if keyword. The code to execute sits inside curly braces {}.

Java 25
public class TemperatureCheck {
public static void main(String[] args) {
int currentTemperature = 35;
int threshold = 30;
// Simple if statement
if (currentTemperature > threshold) {
System.out.println("Warning: It is hot outside!");
}
System.out.println("System check complete.");
}
}
  • Line 7: The condition currentTemperature > threshold is evaluated. Since 35 is greater than 30, the result is true.

  • Line 8: Because the condition was true, we enter the block and print the warning.

  • Line 11: This line runs regardless of the temperature because it is outside the if block. ... ...

Handling the alternative with