A Java control-flow statement selects or repeats work using typed values and boolean conditions.
Values and control flow
Variables and branches
A variable has a type and a value. A condition selects which branch executes.
int score = 72;
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Try again");
}Practice
Change the score to 49 and predict the output. Then write a loop that prints the values from 1 through 5.
Connected lessons
Continue with Java arrays and bounds, Java Tutorial.
Make each branch cover a deliberate boundary
A parcel routing rule might accept a count between 1 and 500. Test the value below the range, the first accepted value, the last accepted value and the value above it. Testing only a middle value cannot reveal an accidental greater-than sign where greater-than-or-equal was required.
A condition can also protect a later operation. In a null check followed by a length check, short-circuit evaluation prevents dereferencing a missing reference only when the null guard is evaluated first. Reversing the expressions changes failure behaviour. Keep guards close to the operation they protect.
A numeric expression is evaluated under the operand types. Assigning the result of int multiplication to long does not repair an overflow that already happened during multiplication. Promote an operand before the operation when the result needs a wider range. Numeric promotion covers that distinction.
A loop needs progress and a stopping rule
For an indexed array scan, the valid condition is index less than length. Less-than-or-equal reaches an invalid position. Incrementing the index establishes progress; removing that increment can make a correct-looking condition run forever.
Nested loops multiply work when each outer iteration scans the entire inner range. Two independent scans do not: their costs add. Count the iterations that actually execute rather than labeling every pair of loops quadratic.
Start with an empty input and a one-element input before large fixtures. They make stopping conditions visible. After the branch and loop basics, use console input to separate invalid input from valid values that fail a business rule.
Common Mistakes
Check empty inputs and invalid values before applying this operation to application data. State whether a method edits shared state or returns a separate value.
