if / else and else if
Part of: Boolean Expressions & if Statements
Two-Way Decisions with else An if/else statement chooses between exactly two paths. When the condition is true, the if body runs; otherwise the else body runs. Exactly one branch executes. Here 7 % 2 is 1, so the condition is false and odd prints. The else has no condition of its own; it is the catch-all for when the if is false. Multi-Way Decisions with else if To choose among more than two options, chain conditions using else if . Java evaluates each condition in order and runs the body of the first one that is true , then skips the rest: With grade = 82, the first test = 90 is false, the second = 80 is true, so it prints B and stops . The remaining branches are never checked. Order Matters Because only the first true branch runs, order is critical . If you reversed the conditions to put = 70 first, then 82 would match it and incorrectly print C. Always arrange ranges from most restrictive to least, or vice versa consistently. The else Is Optional A chain may end without an else. If no condition is true and there is no final else, no branch runs at all: - if alone: zero or one branch runs. - if/else: exactly one of two runs. - if/else if/.../else: exactly one runs (the final else
Challenge: Letter Grade