Conditional Statements
Explore how Java's conditional statements control execution flow by using if, else, else if, and switch constructs. Understand decision-making processes, block scope, and when to choose between if and switch for efficient, clear code.
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.
We define the condition inside parentheses () immediately after the if keyword. The code to execute sits inside curly braces {}.
Line 7: The condition
currentTemperature > thresholdis evaluated. Since 35 is greater than 30, the result istrue.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
ifblock. ... ...