Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
Decision-making for the OCP Java 21 exam: statements and blocks, if, else if and else, braces versus indentation, the dangling else, pattern matching with instanceof, pattern variables, conditions after &&, null handling, supported types and flow scoping.
kvi5hnuCode Sprout team member8 min readOn this page
Programs make decisions at runtime: suggest a coat when it is cold, handle a number differently from a string. This chapter covers Java's decision-making statements. It starts with if/else and pattern matching for instanceof, which tests a type, casts and declares a variable in one step. Pattern matching was finalized in Java 16, and Java 21 relaxed its rules further. The exam tests it heavily, especially its unusual scoping rule.
Statements and blocks
A statement is a complete unit of execution that ends with a semicolon. A block is zero or more statements in braces, and it can go anywhere a single statement can:
patrons++; // a single statement
{ // a block containing the same statement
patrons++;
}
Control-flow statements such as if, while and for take one statement as their body, and that statement can be a block. That's why braces are optional for a one-line body. It's also the source of a classic exam trap.
The if statement
if (tempC < 10) {
System.out.println("Wear a coat");
coatTips++;
}
The condition in parentheses must be a boolean expression. Java never converts numbers to boolean, so if (count) and if (count = 5) don't compile when count is an int.
Braces, not indentation
if (tempC < 10)
System.out.println("Wear a coat");
coatTips++; // NOT part of the if: always runs
Indentation means nothing to the compiler. Without braces, only the first statement after the condition belongs to the if. On the exam, trace the braces and ignore the indentation.
A semicolon right after the condition is an empty statement: if (ready); launch(); always launches, because the if controls only the empty ;. It compiles; javac -Xlint warns "empty statement after if".
else and else if
else gives the alternative path, and else if chains several conditions:
if (tempC < 10) {
System.out.println("Wear a coat");
} else if (tempC < 20) {
System.out.println("Wear a sweater");
} else {
System.out.println("Wear a T-shirt");
}
The conditions are checked top to bottom, and only the first one that is true runs. Order matters. If the chain tested tempC < 20 first, a reading of 5 °C would get "Wear a sweater", and the coat branch could never run. The compiler doesn't warn about that.
else if isn't a separate keyword. It's an else whose single statement happens to be another if.
The dangling else
When if statements are nested without braces, an else belongs to the nearest if that doesn't have one yet:
if (a)
if (b) System.out.print("ab");
else System.out.print("else"); // pairs with if (b), despite the indentation
With a = false, nothing prints. With a = true and b = false, else prints. An else with no if to attach to doesn't compile.
Pattern matching with instanceof
Before Java 16, using an object as a more specific type took two steps, a test and a cast:
void compare(Number reading) {
if (reading instanceof Integer) {
Integer whole = (Integer) reading;
System.out.print(whole.compareTo(7));
}
}
Pattern matching merges them. Add a variable name after the type:
void compare(Number reading) {
if (reading instanceof Integer whole) {
System.out.print(whole.compareTo(7));
}
}
Integer whole is a type pattern, and whole is a pattern variable. If reading refers to an Integer, the test is true and whole refers to the same object, already typed as Integer. The cast happens only when the test succeeds, so it can never throw a ClassCastException.
Adding conditions
Because the pattern variable is assigned the moment the test succeeds, it can be used further along the same condition, after &&:
if (reading instanceof Integer whole && whole.compareTo(7) > 0) {
System.out.print(whole);
}
null never matches
instanceof is false for null, with or without a pattern. That makes pattern matching a safe null check too:
String nothing = null;
if (nothing instanceof String s && s.length() > -1) {
System.out.println("never printed, and no NullPointerException");
}
Reassigning a pattern variable
A pattern variable is an ordinary local variable, so it can be reassigned, but that's bad practice. You can forbid it with final:
if (reading instanceof Integer whole) {
whole = 10; // compiles, but don't do it
}
if (reading instanceof final Integer whole) {
whole = 10; // DOES NOT COMPILE
}
A pattern variable can't reuse the name of a local variable that's already in scope. It can share the name of a field, and then it shadows the field.
Which types are allowed
The pattern's type must be compatible with the expression's type, by the same rules as instanceof (article 10):
Number height = Integer.valueOf(123);
if (height instanceof Integer i) { } // OK: a subtype
if (height instanceof Number n) { } // OK in Java 21: the same type
if (height instanceof Object o) { } // OK in Java 21: a supertype (matches anything but null)
if (height instanceof Runnable r) { } // OK: Number isn't final, so a subclass might implement it
if (height instanceof String s) { } // DOES NOT COMPILE: Number and String are unrelated
Flow scoping
A pattern variable is in scope wherever the compiler can prove the match succeeded, and nowhere else. This is called flow scoping. Unlike ordinary block scope, it depends on how control can flow through the code.

if (reading instanceof Integer whole || whole.compareTo(7) > 0) // DOES NOT COMPILE
With ||, the right side runs only when the test failed, so whole was never assigned there. The same applies to &, which evaluates both sides regardless of the result. Only && guarantees a successful match on its right side.
if (reading instanceof Integer whole)
System.out.print(whole.intValue());
System.out.print(whole.intValue()); // DOES NOT COMPILE: the match isn't guaranteed here
But this compiles:
void printWholeReadings(Number reading) {
if (!(reading instanceof Integer whole))
return;
System.out.print(whole.intValue()); // OK
}
The only way to reach the last line is for the test to have succeeded, because every other path returned. So whole is in scope after the if. The same works when the if body throws an exception, and with a loop like while (!(o instanceof String s)) { ... } followed by code that uses s. It does not work if the if body can complete normally, for example by just printing something.
It helps to read the negated form as an if/else:
| Form | Where whole is in scope |
|---|---|
if (x instanceof T whole) { A } else { B } | A only |
if (!(x instanceof T whole)) { A } else { B } | B only |
if (!(x instanceof T whole)) return; then more code | the code after the if |
x instanceof T whole && cond(whole) | the right side of && |
x instanceof T whole ? use(whole) : other | the true branch of the ternary |
Two separate if statements can each declare a pattern variable with the same name. Their scopes don't overlap.
What's current
- Pattern matching for
instanceofhas been final since Java 16. Record patterns are final in Java 21. - Java 22 finalized unnamed patterns (
_). Primitive types ininstanceofare still a preview through Java 27.
Exam traps from this article
A complete example
public class Solution {
static String clothing(int tempC) {
if (tempC < 10) {
return "Wear a coat";
} else if (tempC < 20) {
return "Wear a sweater";
} else {
return "Wear a T-shirt";
}
}
// Old style: test, then cast.
static String describeOld(Object value) {
if (value instanceof String) {
String s = (String) value;
return "text of length " + s.length();
}
return "not text";
}
// Pattern matching: test, cast and declare in one step, with an extra condition after &&.
static String describe(Object value) {
if (value instanceof String s && !s.isBlank()) {
return "text \"" + s.strip() + "\"";
} else if (value instanceof Integer i) {
return "whole number, doubled " + i * 2;
} else if (value instanceof Number n) { // same idea, broader type
return "number " + n.doubleValue();
}
return "something else: [" + value + "]";
}
// Flow scoping: after the early return, the compiler knows reading is an Integer, so whole is in scope.
static int tripleIfInteger(Number reading) {
if (!(reading instanceof Integer whole)) {
return -1;
}
return whole * 3; // whole is in scope here
}
public static void main(String[] args) {
for (int t : new int[] {8, 13, 20}) {
System.out.println(t + " -> " + clothing(t));
}
System.out.println(describeOld("fig") + " | " + describeOld(42));
Object[] samples = {" Pear ", " ", 7, 2.5, null};
for (Object sample : samples) {
System.out.println(describe(sample));
}
System.out.println(tripleIfInteger(5) + " " + tripleIfInteger(5.5));
// Braces matter, indentation does not: only the first statement belongs to the if.
int visitors = 0;
boolean open = false;
if (open)
visitors += 10;
visitors += 1; // always runs
System.out.println("visitors=" + visitors);
}
}
Output:
8 -> Wear a coat
13 -> Wear a sweater
20 -> Wear a T-shirt
text of length 3 | not text
text "Pear"
something else: [ ]
whole number, doubled 14
number 2.5
something else: [null]
15 -1
visitors=1
Points to notice:
" Pear "passes both conditions. The blank string" "matchesStringbut fails!s.isBlank(), so it drops through to the lastreturn.7is autoboxed to anIntegerand2.5to aDouble. TheIntegerbranch comes first, so7never reaches theNumberbranch.nullfails everyinstanceoftest, so there's noNullPointerException.tripleIfInteger(5.5)returns early. Only anIntegerreaches the line that useswhole.visitors=1: the indented second line isn't part of theif.
Common questions
Is pattern matching just syntax sugar for a cast? Mostly. It does the same type check and cast. The gains are less code, no way to forget the cast or cast to the wrong type, and the compiler checking where the variable can be used.
Can I use the pattern variable after || if I negate the test?
Yes: !(x instanceof String s) || s.isEmpty() compiles. The right side of || runs only when the left side is false, which means the match succeeded.
Why can't I declare a pattern variable named like an existing local?
Pattern variables are locals, and Java doesn't let one local shadow another that's still in scope (article 7). A field with the same name is fine, and this.name still reaches it.
Does if (o instanceof Object x) do anything useful?
It's true for every non-null object. It compiles in Java 21 but is rarely useful. It mainly appears in exam questions about which patterns are allowed.
Should I always use braces? In real code, yes. Most style guides require them because they prevent the indentation trap. The exam leaves them out on purpose.
Summary
- Control-flow statements govern a single statement, which can be a block. Without braces, only the first statement belongs to the
if. - The
ifcondition must be aboolean.else ifchains run only the first branch whose condition istrue, and anelsepairs with the nearest unmatchedif. x instanceof Type nametests, casts and declares a pattern variable. It never matchesnull, and it never throws aClassCastException.- The pattern's type must be compatible with the expression's type. Since Java 21 it may also be the same type or a supertype.
- Flow scoping: a pattern variable exists only where the match is guaranteed. That includes the right side of
&&and the code after anif (!(...)) return;, but not the right side of||or&.
Practice quiz
Test yourself with the if/else and pattern matching quiz: 10 exam-style questions with explanations.
Previous: Java Equality, Relational, Logical and Ternary Operators (OCP 21)
Next: Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
Related reading
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
- Java Pattern Matching: switch Patterns, Record Patterns and Guards
- Java Sealed Classes and Interfaces: Controlling Inheritance

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.