Concepts / Java Control Flow with if-else Statements

Java Control Flow with if-else Statements

A switch statement chooses one block of code based on the value of an integer variable, and each case label is associated with a specific value

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

Predicting a Switch Before Reading the Mechanism

A switch statement lets a program choose among several blocks of code based on the value of one variable. Instead of writing a long chain of separate checks against the same value, you name the variable once and list the possible values as cases. This article works through a traditional Java switch, then asks you to predict its behavior before explaining the mechanism behind it. It then covers the if-else statement, which chooses between two alternatives using a boolean expression.

Keep the variable N in mind as the running example. The switch is written in parentheses after the keyword switch, and each case label is followed by a value and a colon. The statements after that colon are the code for that case. Read the structure once for its shape. You will trace it step by step in the sections that follow.

What do you think happens?

Suppose N holds the value 6 when this switch runs. Which message or messages print?

  • Only Six

  • Six and then Other

  • Other only

  • Nothing prints

Reveal answer
Answer:

Only Six

The label case 6 matches the value 6, so execution starts at the statements under that label. The break after the Six message exits the switch, so the default branch never runs.

If your prediction was different, that gap is useful. The next sections explain how the switch chooses where to start, what it runs once it gets there, and where it stops. The same rules govern the trace you will follow.

Parts of a Switch Statement

A switch statement has a fixed structure. The keyword switch is followed by a parenthesized expression, here the variable N. Inside a pair of braces, the switch contains multiple case labels. Each label is followed by a value and a colon, and each case is associated with a specific value. The statements after that colon are the code for that case. A switch may also include one optional default label, which covers values that no case handles.

java
Output
Six
Notes on the code
  • int N = 6; holds the value the switch will compare
  • switch (N) names the expression evaluated once
  • case 1: through case 8: are case labels, each with a value and a colon
  • case 2:, case 4:, and case 8: are stacked above one block, so they share it
  • break ends the statements of a case
  • default: is the optional block for values no case handles
Definition

The switch expression is the parenthesized value the program evaluates. A case label is a value followed by a colon that marks where a block of statements begins. A break is the keyword that ends a case's block. The default label marks the optional block that runs only when no case value matches.

Tracing Which Case Matches

When a switch runs, the program evaluates the variable in parentheses and compares its value against the case labels. When one label matches, execution jumps to the statements under that label. The statements under other labels are skipped. Matching decides only where execution starts. It is important to separate the choice of entry point from what happens afterward.

Evaluate NN holds 6Match case 6 labelCase 6 statementsprints SixbreakAfter switchcomparematchesreachesexits switch
Given N = 6, which label does execution enter, and where does it stop?

The diagram shows one route through the switch. The variable is compared to a label, and a match sends execution into that label's statements. The break then sends execution out of the switch entirely. Labels that were checked and did not match are never run. Read the diagram as a route, not as a list of every line in the code.

Stacked labels show that several values can share one block. Labels written one after another with no statements between them all lead to the same group of statements. In the generated example above, case 2:, case 4:, and case 8: sit above one println, so any of those three values prints the same message.

Default and Unmatched Values

The default label is optional. When it is present, its block runs only when the switch variable matches none of the case values. Default is typically used for unexpected or unhandled values. The switch first checks the case labels, and default is used only if none of them matched. Its position in the code does not change this matching rule.

In a switch that handles the values 1 through 9 with special cases, any value outside the listed cases falls to default. That includes values such as 7 that are in range but not listed, as well as values outside the range 1 to 9. Because the listed cases form the explicit choices, default catches everything else.

What Happens Without a break

The break keyword is what ends a case's block. A case statement does not have a break by default, so the programmer must write one. If a case's statements do not end with break, execution does not stop at the end of that case. It continues into the statements of the next case below it. This is called fall-through, and it is one of the most common sources of unexpected output in a switch.

java
Output
One
Two
Notes on the code
  • The case 1 block has no break
  • After One prints, execution continues into the case 2 statements
  • Only the break in the case 2 block stops the switch
Evaluate NN holds 1Case 1 statementsprints OneCase 2 statementsprints TwobreakAfter switchmatches case 1no breakreachesexits switch
With N = 1 and no break after the case 1 message, which statements run before the switch ends?
  • Common mistake

    Assuming a matched case stops the switch on its own

    What it looks like
    case 1: println("One"); with no break, followed by case 2: println("Two"); break;
    Why it fails

    A case has no break by default, so execution continues into the next case's statements after the first message prints.

    Do this instead

    End each case that should stop on its own with a break, or intentionally leave the break out only when fall-through is the goal.

  • Common mistake

    Expecting default to run whenever a listed case is skipped

    What it looks like

    A value of 6 matches case 6, yet the programmer expects the default message to print as well.

    Why it fails

    Default runs only when no case value matches. A matched case's statements run, and the switch then stops at its break.

    Do this instead

    Check whether a case label matches before looking for default output.

Choosing Between Two Alternatives

An if-else statement gives a program two possible paths. It has a boolean expression, an if block, and an else block. The boolean expression determines which path is selected. When the expression is true, the statement or block after if runs. When it is false, the statement or block after else runs. The two alternatives form one conditional choice.

years > 1if blocktrue branchStatement afterelse blockfalse branchtruefalsecontinuescontinues
When years > 1 is true versus false, which block runs, and where do the paths rejoin?

The source example separates cases for more than one year and for one year. The condition years > 1 controls which message block runs. A final formatting statement placed after the closing brace of the if-else is outside the conditional choice, so it runs regardless of which alternative was chosen.

Grouping Statements with Braces

Either alternative can be a block containing multiple statements, and braces make the boundaries of that block visible. A block groups statements so that the condition controls them together. In the source swapping example, the block after if contains a declaration and several assignments. If x is greater than y, those statements work together to exchange the values of x and y. The braces show that all of these statements belong to the if alternative.

java
Output
Year
Done
Notes on the code
  • years > 1 is the boolean expression
  • The braces around the if block group its statements
  • The else block runs because years > 1 is false when years is 1
  • System.out.println("Done") sits after the closing brace, so it runs in either case

Tracing Statements Before and After the Choice

To trace an if-else, work through three locations in order. First evaluate the boolean expression. Second, identify which braces enclose the selected alternative. Third, follow the statements after the closing brace, which run afterward regardless of the condition's result. This is the same procedure whether the condition is true or false.

Worked example

Tracing an if-else with years set to 3

Using the generated if-else code with years = 3, which lines print, and in what order?

  1. 1
    Evaluate the expression

    years > 1 with years = 3 is true.

  2. 2
    Select the alternative

    The if block runs, so Years prints. The else block is skipped.

  3. 3
    Run the statements after

    The line printing Done is after the closing brace, so it runs next.

Result

Years, then Done

  • Common mistake

    Assuming every indented line is inside the if block

    What it looks like
    if (years > 1) System.out.println("Years"); followed by an indented System.out.println("Extra"); on the next line with no braces
    Why it fails

    Without braces, only the statement directly after if belongs to the conditional choice. Indentation does not change which statements are controlled.

    Do this instead

    Use braces around every statement that should run only under the condition.

  • Common mistake

    Reading the wrong path when the boolean expression is misread

    Why it fails

    A true or false result selects the entire alternative. Misreading the comparison makes the whole block appear to run or be skipped incorrectly.

    Do this instead

    Evaluate the boolean expression first and write down true or false before tracing either block.

Practice Tracing Switches and if-else Blocks

MEDIUM

Trace the switch below for N = 9 and then for N = 7. For each value, list the messages that print in order. Explain which label matched or whether default ran.

int N = 9;
switch (N) {
    case 1: System.out.println("One"); break;
    case 2: case 4: case 8: System.out.println("Two, four, or eight"); break;
    case 5: System.out.println("Five"); break;
    case 6: System.out.println("Six"); break;
    default: System.out.println("Other");
}
Hints
  • Start by checking whether 9 appears as a case label.
  • Remember that default runs only when no case value matches.
  • Then repeat with N = 7 and compare the two results.
EASY

Given int years = 2; with an if-else that uses the condition years > 1, one block prints Years and the other prints Year. Then a final statement prints Done after the closing brace. Predict the full output, then identify which statements belong to the conditional choice and which run afterward.

Hints
  • Evaluate years > 1 first.
  • Only the statements inside the selected block run as part of the choice.

Key Takeaways

  • A switch chooses one block by matching the value of one expression against case labels. Matching selects an entry point, and execution then runs downward until a break or the closing brace.
  • A case has no break by default, so a missing break causes fall-through into the next case's statements. Default runs only when no case value matches.
  • An if-else statement uses a boolean expression to choose between an if block for true and an else block for false.
  • Braces group multiple statements under a condition. Statements after the closing brace run regardless of which alternative was selected.