Java if Statements
Learn to make your programs decide: execute code only when a Boolean condition is true, branch with else, and chain logic with else if.
What Is an if Statement?
An if statement is the most fundamental control structure in Java. It lets your program make decisions by testing a Boolean condition and executing a block of code only when that condition evaluates to true.
Boolean Conditions: The Gateway
Every if statement relies on a Boolean expression: an expression that evaluates to either true or false. Java provides several comparison operators to build these expressions:
Why if Statements Matter
Without conditional logic, programs can only execute instructions sequentially: line after line, with no ability to adapt. The if statement unlocks three critical capabilities:
The Syntax of an if Statement
if: tells Java a conditional block follows.( ): contain the Boolean expression to test.{ }: wrap the body. If the condition is true, every statement inside runs. If false, the entire block is skipped.How an if Flows
Adding an else Branch
When you need to do one thing if a condition is true and a different thing if it is false, add an else clause:
Chaining with else if
When there are more than two possibilities, chain multiple conditions using else if. Java evaluates them top to bottom and executes the first block whose condition is true:
if vs if-else vs else if
How to Apply if Statements
Example 1: Simple if
Example 2: if-else in Action
Example 3: else if Chain
Common Mistakes
Summary Comparison
| if | if-else | else if chain | |
|---|---|---|---|
| Branches | 1 | 2 | N |
| Blocks executed | 0 or 1 | Exactly 1 | Exactly 1 (with else) |
| Mutual exclusion | No | Yes | Yes |
| Requires else? | No | Yes | Optional (recommended) |
| Use when | One optional action | Two alternatives | Multiple categories |
Question 1 of 5
What is printed by the following code?
Question 2 of 5
What is printed by the following code?
Question 3 of 5
Which of the following will cause a compile-time error in Java?
Question 4 of 5
What does this code print?
Question 5 of 5
What is the value of grade after this code runs with \(score = 85\)?