2.3 - if Statements
Selection statements change the normal sequential flow of a program based on a condition.
An if statement is the basic selection statement. It runs a block of code only when a boolean expression is
true.if (age >= 18) { System.out.println("You can vote."); }
This is called one-way selection, there’s only one path, and the code either runs or it doesn’t.
When the condition is false, Java skips the body and moves on to whatever comes after the
if. Either way, the program then keeps going in order from there.int temp = 45; if (temp < 50) { System.out.println("Wear a jacket."); } System.out.println("Have a good day."); // when temp is 45, prints: // Wear a jacket. // Have a good day. // when temp is 70, prints only: // Have a good day.
Two-way selection (an
if-else statement) gives you two paths: one for when the condition is true, another for when it’s false.if (age >= 18) { System.out.println("You can vote."); } else { System.out.println("You can't vote yet."); }
With
if-else, exactly one of the two bodies always runs: the if body when the condition is true, the else body when it’s false.Common Mistakes
A semicolon right after the condition ends the
if statement there. The code in the braces is no longer part of it, so it runs every time.int score = 40; if (score > 90); // the semicolon ends the if statement right here { System.out.println("Great job!"); // runs no matter what }
Without braces, only the first statement after the condition belongs to the
if. Indenting the next line doesn’t change that.int score = 40; if (score > 90) System.out.println("Great"); System.out.println("job!"); // not part of the if, always runs // prints only: job!