The if Statement
Part of: Boolean Expressions & if Statements
Making Decisions An if statement runs a block of code only when a boolean expression is true. This is the simplest form of conditional control flow : the program chooses whether to execute a section based on a condition. Syntax The condition inside the parentheses must be a boolean expression. If it evaluates to true, the body in braces executes; if false, the body is skipped entirely and the program continues after the closing brace. A Concrete Example If score is 85, the condition score = 60 is true, so it prints You passed! then Done. If score were 40, the condition is false, the print is skipped, and only Done appears. Braces and the Single-Statement Trap You may omit the braces when the body is a single statement, but the AP exam and good style strongly favor always using braces : The indentation here is misleading. Only the first println is controlled by the if. The second runs unconditionally because it is outside the (invisible) single-statement body. Braces prevent this bug. No Semicolon After the Condition Watch for an empty statement bug: The stray semicolon makes the if do nothing, and the block then runs every time. Always connect the condition directly to a brace. Flo
Challenge: Pass or Silent