The 1Z0-829 exam objective 2.1 — Branching — is where you learn to make your Java programs make decisions. Without branching, every program would run the same way every time, like a recipe that ignores whether the oven is actually on. Mastering if, if-else, and switch statements is the first step toward writing code that reacts intelligently to different inputs and situations.
Jump to a section
A simple way to picture Controlling Program Flow
A Security Supervisor at a busy international airport manages the flow of passengers through the security checkpoint. The supervisor does not decide who flies — that is the airline's job. Instead, they decide who gets through the checkpoint to the gates and in what order. This is pure flow control.
Passengers arrive in a single queue. The supervisor has a set of rules. First, they check: does this passenger have a boarding pass? If yes, they move to the ID check. If no, the passenger is sent back to the ticket counter (a branch). At the ID check, the supervisor asks: is this person on the no-fly list? If yes, security is called and the process stops entirely (like a return statement). If no, the passenger proceeds to the X-ray machine.
At the X-ray, the supervisor has a second queue. They examine each bag. They might say: if the bag has a laptop, take it out first (an if condition). If the bag has a water bottle, discard the water (a nested if). If the bag has nothing suspicious, let it pass (the else path). Every passenger follows exactly one path through these checks — never two. That is a switch-like decision structure.
The supervisor cannot change who is on the flight. They can only decide who gets through each checkpoint. That single, limited power — controlling the flow of passengers based on conditions — is exactly what "Controlling Program Flow" means in Java. You are the supervisor. Your code is the queue of passengers. Your if statements are the checkpoint rules. And you must ensure every passenger (every line of code) reaches the right gate without chaos.
Controlling program flow means telling your Java program which lines of code to run and in what order, based on conditions you define. By default, Java runs code line by line from top to bottom — this is called sequential execution. But real programs need to make choices. They need to say: if the user is logged in, show their profile; otherwise, show the login page. That choice is a branch in the flow.
The most fundamental branching tool is the if statement. The syntax is: if (condition) { // code to run if condition is true }. The condition must be a boolean expression — that is, something that evaluates to either true or false. A boolean is a data type that can only hold those two values. For example, int age = 17; if (age >= 18) { System.out.println("Adult"); } would not print anything because the condition age >= 18 is false.
You can add an else clause to handle the false case: if (age >= 18) { System.out.println("Adult"); } else { System.out.println("Minor"); }. Now, no matter what age is, exactly one branch runs. This is called an if-else statement. You can chain multiple conditions with else if: if (age < 13) { System.out.println("Child"); } else if (age < 18) { System.out.println("Teen"); } else { System.out.println("Adult"); }. The program checks each condition in order. The first one that is true causes its block to run. Once a block runs, the rest are skipped. This is why order matters: if you put age < 18 before age < 13, a 10-year-old would be labelled a Teen incorrectly.
For situations where you compare a single variable against many possible exact values, Java provides the switch statement. The syntax is: switch (variable) { case value1: // code; break; case value2: // code; break; default: // code; }. The variable is evaluated once. Then the program jumps directly to the matching case label. The break keyword exits the switch block — without it, execution "falls through" to the next case, which is a common source of bugs. The default case runs if no other case matches. Starting in Java 14, switch can also be used as an expression that returns a value, using the arrow syntax: int result = switch (day) { case "MONDAY", "FRIDAY" -> 1; default -> 0; };. This is called a switch expression, and it must be exhaustive — every possible value must be covered, or you must include a default.
Why do we need these tools? Without them, every program would be a straight line: no user input handling, no error checking, no logic. Branching is what separates a to-do list from a decision engine. It lets your code respond differently to different data, which is the essence of programming.
Additionally, Java provides break and continue inside loops (like for or while), not just in switch. break exits the entire loop immediately. continue skips the rest of the current iteration and jumps to the next loop cycle. These are flow control tools that can make loops more efficient but also harder to read if overused. The exam loves asking about where break and continue are valid and what they affect.
Evaluate the condition
Java evaluates the boolean expression inside the parentheses of the if statement. For example, if (score > 70) — the expression score > 70 is computed first, producing either true or false. This is the only thing that determines which branch runs next.
Choose the branch
If the condition is true, Java executes the block of code immediately following the if. If false, it skips that block and checks the next else if condition (if any) or executes the else block. Exactly one path is taken.
Execute the block
Java runs every statement inside the chosen block in order, from top to bottom. Once the block ends (at the closing brace), execution continues after the entire if-else structure. No other branch runs.
Handle fall-through in switch (if applicable)
When using a traditional switch with break statements, after a matching case block runs up to a break, execution jumps to the end of the switch. Without a break, execution continues into the next case block — that is fall-through. You must intentionally place break to stop it.
Return a value from a switch expression (if used)
In a switch expression using arrow syntax, each branch produces a value. That value is returned from the entire switch expression. The switch expression is then used in an assignment or as part of a larger expression. The compiler checks that all cases are covered.
A junior developer at a financial services company is tasked with building a loan approval module. The system receives a loan application containing the applicant's credit score, annual income, and existing debt. The developer must write Java code that decides whether to approve, decline, or flag the application for manual review.
The developer writes a method called evaluateLoanApplication that takes these three numbers as parameters. They start with the most restrictive condition: if the credit score is below 600, the application is immediately declined. They write: if (creditScore < 600) { return "Declined"; }. The return statement here acts like an early exit — it stops the method and sends back the result. No further checks run. This is a real-world use of early return to short-circuit unnecessary logic.
If the credit score is 600 or above, the developer then checks the debt-to-income ratio. They write: else if (totalDebt / annualIncome > 0.43) { return "Flagged for Review"; }. This condition uses a division and a comparison. If the ratio is too high, the application is not automatically declined but sent to a human officer. That is a branch that creates a new state — not a simple yes or no.
If the debt ratio is fine, the final check is income level. The developer uses a switch expression on a tier enum: int tier = switch (incomeLevel) { case LOW -> 0; case MEDIUM -> 1; case HIGH -> 2; }. They then use that tier to determine the maximum loan amount. The switch expression ensures that every possible income level is handled — if a new level is added later, the code will not compile without a matching case. That is an example of switch exhaustiveness protecting against bugs.
In the real world, this code will be deployed to a server that processes thousands of applications per hour. Each if statement is a decision point that must be correct. A single misplaced else could approve a loan for someone with a 450 credit score. The developer also adds logging at each branch so the team can audit decisions later. They write something like: if (creditScore < 600) { logger.info("Application declined: low credit score"); return "Declined"; }. The logging itself does not affect the flow, but it is placed inside the branch to record which path was taken.
The key takeaway for a junior developer is that flow control is not just academic — it is the logic that drives every business rule. The loan approval module, a shopping cart checkout flow, a login system — they all rely on the exact same if-else and switch structures. Learning to write them cleanly and correctly is a daily skill.
The 1Z0-829 exam tests your understanding of branching in three main ways: pattern matching in switch, the precise rules of break and continue, and the difference between switch statements and switch expressions. You will see multiple-choice questions that show you a code snippet and ask what the output is, or whether the code compiles. - Pattern matching in switch: Since Java 17, you can use switch with pattern matching for type checks. For example: switch (obj) { case String s -> System.out.println(s.length()); case Integer i -> System.out.println(i * 2); default -> System.out.println("Unknown"); }. The exam loves to test that the type of the variable used in the case (like s or i) is in scope only within that branch. They also test that null handling is required: if obj is null and there is no null case, the switch throws a NullPointerException. Always check if a null case is present when the variable can be null. - The fall-through trap: A classic exam trick is to omit a break in a switch statement. For example: int x = 2; switch (x) { case 1: System.out.print("A"); case 2: System.out.print("B"); case 3: System.out.print("C"); break; default: System.out.print("D"); }. What prints? The answer is "BC" because case 2 matches, then execution falls through to case 3 (printing "C") before the break at the end of case 3 stops it. The break at case 3 does not prevent the fall-through from case 2 to case 3. Memorise: fall-through continues until a break or the end of the switch. - Switch expression exhaustiveness: In a switch expression (using arrow syntax or colon syntax with yield), the compiler requires that every possible value of the selector expression is covered. For a boolean selector, you must have both true and false cases, or a default. For an enum, you must cover all enum constants or include a default. If you miss any, the code will not compile. This is a common trap — the exam will present a switch expression missing one enum constant and ask if it compiles. It does not. - The scope of break and continue: break can be used in switch statements and loops (for, while, do-while). continue can only be used in loops, never in switch. The exam will show a continue inside a switch and ask if it compiles — it does not, because continue is not valid there. Also, labelled break and continue exist: you can give a loop a label (outer: for(...)) and then break outer; to break out of an outer loop from an inner loop. This is rarely used but appears on the exam. - Ternary operator vs if-else: The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand for simple if-else assignments. The exam tests that it is an expression that must return a value and that both branches must have compatible types. It is not a full replacement for if-else, especially when multiple statements are needed. - Boolean expressions in conditions: The exam loves to test operator precedence. For example, if (a = b) instead of if (a == b) — the first is an assignment, not a comparison, and in Java, it would be a compile-time error because the result of assignment is not boolean unless a and b are boolean. Remember: in if conditions, the expression must be boolean. Any other type causes a compilation error.
An if condition must evaluate to a boolean value — anything else causes a compilation error in Java.
In a switch statement, omitting a break causes fall-through to the next case, which continues until a break or the end of the switch block is reached.
A switch expression must be exhaustive — every possible value of the selector must be covered, or a default branch is required.
The continue keyword is only valid inside loops (for, while, do-while) and cannot be used inside a switch statement.
Pattern matching in switch allows you to match on the type of an object and bind a variable in the case branch, but null must be handled separately or it will throw a NullPointerException.
The ternary operator (condition ? valueIfTrue : valueIfFalse) is an expression that must return a value and both branches must have compatible types.
These come up on the exam all the time. Here's how to tell them apart.
if-else Statement
Evaluates a boolean condition — can handle ranges and complex logic (e.g., score > 70).
Each condition is checked in order until one is true.
There is no fall-through mechanism; exactly one branch runs.
switch Statement
Evaluates a single expression against exact values — best for discrete constants (e.g., day of week).
Jumps directly to the matching case without sequential checks.
Has fall-through behaviour unless break is used; can be intentional or a bug.
switch Statement
Does not produce a value — used for side effects like printing or assignment.
Does not require exhaustiveness — missing cases silently do nothing.
Uses break to prevent fall-through, or colon-case syntax.
switch Expression
Produces a value that can be assigned to a variable or used in an expression.
Must be exhaustive — every possible value must be covered or a default provided.
Uses arrow syntax (->) or colon-case with yield; no break needed.
break (in loops)
Exits the entire loop immediately when encountered.
After break, execution continues at the first statement after the loop.
Can be used with a label to break out of an outer loop from an inner one.
continue (in loops)
Skips the rest of the current iteration and jumps to the next loop cycle.
After continue, the loop's update expression (in for loop) still runs.
Cannot be used to skip to an outer loop; it only affects the innermost loop it is in.
Mistake
An if statement can evaluate any expression, like an integer, and treat zero as false.
Correct
In Java, an if condition must be a boolean expression — it must evaluate to true or false. Unlike C or Python, integers cannot be used directly as conditions. if (0) will not compile.
Many beginners come from other languages where truthy/falsy values exist. Java is strict: only boolean expressions are allowed in if conditions.
Mistake
In a switch statement, the default case always runs last, no matter where it is placed.
Correct
The default case runs only if no other case matches. Its position in the switch block matters only for fall-through. If default is placed before other cases and a match is found later, default runs first if fall-through occurs, but never just because it is at the end.
Default is often placed at the end by convention, leading learners to believe it has a special final position. In reality, it is a regular case label with no special ordering power.
Mistake
A switch expression and a switch statement are the same thing, just different syntax.
Correct
A switch statement performs actions and does not return a value. A switch expression returns a value and must be exhaustive (cover all possible values). They are fundamentally different constructs with different compilation rules.
The arrow syntax can be used in both, making them look similar. Beginners conflate them because the same keyword 'switch' is used.
Mistake
If you put a break inside a loop inside a switch, it breaks out of the switch, not the loop.
Correct
A break always breaks out of the nearest enclosing switch, loop, or labelled block. If a break is inside a loop that is inside a switch, it breaks the loop, not the switch. To break the switch, the break must be directly inside the switch block.
The proximity rule is often misunderstood. Beginners think break always affects the switch because they learn break in the context of switch first.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
Yes, but only for a single statement. Without braces, only the very next line is considered part of the if block. It is a common source of bugs, so using braces always is strongly recommended.
== compares primitive values or object references (whether they point to the same memory location). equals() compares the actual content of objects (like whether two Strings have the same characters). For String comparison in if statements, always use equals(), not ==.
Not always. If the selector is an enum and you cover all constants, the default is optional. For other types like String or int, the default is technically not required for the switch expression to compile in all cases, but the compiler will enforce exhaustiveness in pattern-matching switch. It is safest to always include a default.
No. continue is only valid inside a loop (for, while, do-while). Using it inside a switch (outside of any loop) will cause a compilation error. If the switch is inside a loop, continue goes to the next iteration of the loop, not the switch.
Execution falls through to the next case, meaning the code in the subsequent case(s) runs as well, until a break is encountered or the switch ends. This can cause unintended behaviour unless you deliberately want fall-through.
No, the performance difference is negligible and should not influence your choice. The decision between ternary and if-else should be based on readability: ternary is best for simple, single-value assignments; if-else is clearer for complex logic or multiple statements.
You've finished Controlling Program Flow. Continue through the 1Z0-829 study guide to build a complete picture of the exam.
Done with this chapter?