Unit 2.3: if Statements
Learning Objective
2.3.A: Develop code to represent branching logical processes by using selection statements and determine the result of these processes.
Essential Knowledge
- Selection statements change the sequential execution of statements
- if statements affect the flow of control by executing different segments of code based on Boolean expressions
- One-way selection (if statement) executes code under certain conditions
- Two-way selection (if-else statement) chooses between two code segments
Selection statements allow programs to make decisions and respond dynamically to different conditions!
Sequential vs Selection Execution
Sequential Execution (Default)
Normally, Java executes statements one after another in order:
Selection Execution
Selection statements change the sequential execution by allowing the program to choose which statements to execute based on conditions:
Selection statements give programs the power to make decisions and branch to different code paths!
One-way Selection (if Statement)
Syntax
How it Works
- The Boolean expression is evaluated
- If true: the code inside the braces executes
- If false: the code inside the braces is skipped
- Program continues with the next statement after the if block
Example
Output: Since 95 >= 90 is true, both messages inside the if block print, followed by "End of program".
Interactive: One-way Selection
Try These Values:
- 85 (should print the hot weather messages)
- 75 (should skip the if block)
- 80 (exactly 80 - what happens?)
Two-way Selection (if-else Statement)
Syntax
How it Works
- The Boolean expression is evaluated
- If true: execute the if block, skip the else block
- If false: skip the if block, execute the else block
- Exactly one of the two blocks will always execute
Example
Output: Since 16 >= 18 is false, the else block executes.
Interactive: Two-way Selection
Try These Values:
- 85 (should show passing message)
- 65 (should show retake message)
- 70 (exactly 70 - boundary condition)
Common Patterns and Best Practices
Nested if Statements
Multiple Conditions with else if
Best Practices
- Always use braces { } even for single statements
- Test boundary conditions (like exactly equal values)
- Use meaningful variable names in conditions
- Keep conditions simple and readable
Practice and Review
Key Concepts Review
One-way selection: Use when you want to execute code only under certain conditions
Two-way selection: Use when you want to choose between two different actions
Practice Problem
Write an if-else statement that:
- Takes a variable called password
- If the password length is at least 8 characters, print "Strong password"
- Otherwise, print "Password too short"
AP Exam Tips
- Trace through code carefully with given input values
- Pay attention to boundary conditions (>=, >, <=, <)
- Remember that exactly one branch executes in if-else
- Watch for nested if statements and proper indentation