Two-way Selection: if-else Statements
Introduction: 3.3.0
- use
if
andelse
to pick between two possibilities - Can be used with relational operators
boolean myExpr = false;
if (myExpr) {
doSomethingWhenTrue();
} else {
doSomethingWhenFalse();
}
Nested ifs and Dangling else: 3.3.1
- if statements can be nested
- Can sometimes have “dangling else” which could belong to either
- This always belongs to the closest if statement
- Regardless of Indentation
- Use curly brackets to differentiate
- This always belongs to the closest if statement
if (boolean)
if (boolean)
doSomething();
else // THIS BELONGS TO THE SECOND IF
if (boolean) {
if (boolean)
doSomething();
} else {
// BELONGS TO THE SECOND IF
}
Summary: 3.3.3
- if statements can be followed by an
else
to make a 2-way branch- One executed when true, the other when false
- Use 2 test-cases to test both branches and fine errors
- else statements attach to the nearest if
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.