Sub topic 7
Negation and early returns
This chapter assumes you know how instanceof and reference casts work, how &&, || and ! short-circuit, and what a type pattern and its binding variable are (covered in earlier chapters). Here you will learn how a binding variable behaves when the condition is negated. You will also learn how that lets you write guard clauses that leave the variable in scope after the if.
The problem with positive matches
So far the binding variable has lived inside the if body. That works well when the matching case is the main work. Often it is not. A method might handle the odd case first (wrong type, bad input) and then do its real work. Nesting the real work inside an if pushes it to the right and buries the main logic.
static int lengthNested(Object o) {
if (o instanceof String s) {
return s.length();
} else {
return -1;
}
}This is correct, but with more logic the if block grows. The guard-clause style avoids that: reject the bad cases first, then continue at the top indentation level. Negation makes this possible with patterns.
Negating a pattern
You can put ! in front of a pattern match:
if (!(o instanceof String s)) {
// here the test failed, so s is NOT in scope
}The compiler reasons about when each binding variable is definitely matched:
- If
o instanceof String sis true,shas a value. - If
!(o instanceof String s)is false, that means the match was true, soshas a value.
The compiler tracks this for each condition. It records which binding variables are introduced when a condition is true and which when it is false. For a negation, the two sets swap.
| Condition | `s` is in scope when the condition is... | Column | Column |
|---|---|---|---|
| `o instanceof String s` | true | ||
| `!(o instanceof String s)` | false | ||
| `a && b` | true (variables from both sides) | ||
| `a \ | \ | b` | false (variables from both sides) |
The last two rows follow from short-circuiting. An && is true only if both sides are true, so both sides' true-bindings are available afterward. An || is false only if both sides are false, so both sides' false-bindings are available afterward.
The early-return rule
Now the rule that makes guard clauses work. For an if statement with no else, a binding variable that the condition introduces when false is in scope in the statements after the if, provided the if body cannot complete normally. A body cannot complete normally when it always ends in return, throw, break or continue.
The reasoning is the same flow reasoning as before. If the body always leaves, then the code after the if runs only when the condition was false. When !(o instanceof String s) is false, the pattern matched.
static int lengthOrMinusOne(Object o) {
if (!(o instanceof String s)) {
return -1;
}
return s.length();
}Here s is a String after the if, with no cast and no nesting. The method reads top to bottom: reject, then use.
When the body can fall through
If the body can complete normally, the code after the if can run in two situations: the pattern matched, or the pattern did not match and the body ran. The compiler cannot tell which one applies, so it does not put s in scope.
static int brokenLength(Object o) {
if (!(o instanceof String s)) {
System.out.println("not a string");
// no return: execution falls through
}
// Does not compile: s is not in scope here.
// return s.length();
return -1;
}The error message says the symbol s cannot be found. The fix is to end the body with return, throw, continue or break, depending on the context.
Guards that throw or continue
The body does not have to be a return. Throwing is common for argument checks:
static String requireString(Object o) {
if (!(o instanceof String s)) {
throw new IllegalArgumentException("Expected a String but got " + o);
}
return s.trim();
}Inside a loop, continue skips items that do not match:
static int totalLength(List<Object> items) {
int total = 0;
for (Object item : items) {
if (!(item instanceof String s)) {
continue;
}
total += s.length();
}
return total;
}continue cannot complete normally, so s is in scope for the rest of the loop body.
Combining negation with ||
Because || introduces the false-bindings of both operands, you can chain a negated pattern with further checks on the same variable. The right operand of || runs only if the left side was false, which means the pattern matched. So s is usable there:
static String firstWord(Object o) {
if (!(o instanceof String s) || s.isBlank()) {
return "";
}
int space = s.indexOf(' ');
return space < 0 ? s : s.substring(0, space);
}Walk through the three cases:
ois not aString. The left side is true, so||short-circuits and the body returns"". Thes.isBlank()call never runs.ois a blankString. The left side is false, sosis bound.s.isBlank()is true and the body returns"".ois a non-blankString. Both sides are false, so the whole condition is false and the body is skipped. After theif,sis in scope.
This is the mirror image of the && form you saw earlier. Positive patterns pair with &&. Negated patterns pair with ||. The earlier chapter's failing o instanceof String s || s.isEmpty() mixes a positive pattern with ||, which is why it does not compile.
The else branch and the conditional operator
The same logic applies to other constructs. In a negated if with an else, the binding variable is in scope in the else branch:
static String describe(Object o) {
if (!(o instanceof String s)) {
return "not a string";
} else {
return "string of length " + s.length();
}
}The conditional operator follows the same rule. The second operand sees the true-bindings and the third sees the false-bindings:
static int lengthOrZero(Object o) {
return !(o instanceof String s) ? 0 : s.length();
}Name clashes after a guard
A binding variable that is in scope after an if behaves like a local variable declared at that point. You cannot declare another variable with the same name while it is in scope, and you cannot reuse the same binding name in a later pattern.
static String twoChecks(Object a, Object b) {
if (!(a instanceof String s)) {
return "a is not a string";
}
// Does not compile: s is already in scope and cannot be redeclared.
// if (!(b instanceof String s)) { return "b is not a string"; }
if (!(b instanceof String t)) {
return "b is not a string";
}
return s + t;
}Use distinct names when you chain several guards in one method. With the positive form, the first binding goes out of scope at the end of its if, so reusing a name in separate if statements is fine.
A complete runnable example
import java.util.List;
public class GuardDemo {
static int lengthOrMinusOne(Object o) {
if (!(o instanceof String s)) {
return -1;
}
return s.length();
}
static String firstWord(Object o) {
if (!(o instanceof String s) || s.isBlank()) {
return "";
}
int space = s.indexOf(' ');
return space < 0 ? s : s.substring(0, space);
}
static int totalLength(List<Object> items) {
int total = 0;
for (Object item : items) {
if (!(item instanceof String s)) {
continue;
}
total += s.length();
}
return total;
}
public static void main(String[] args) {
System.out.println(lengthOrMinusOne("hello"));
System.out.println(lengthOrMinusOne(42));
System.out.println(lengthOrMinusOne(null));
System.out.println("[" + firstWord("hello world") + "]");
System.out.println("[" + firstWord(" ") + "]");
System.out.println("[" + firstWord(7) + "]");
System.out.println(totalLength(List.of("ab", 1, "cde", 2.5)));
}
}Expected output:
5
-1
-1
[hello]
[]
[]
5The null call returns -1 because instanceof is false for null, so the negated test is true and the guard fires. Guards written this way handle null without a separate check.
Choosing between the two styles
- Use the positive form (
if (o instanceof String s) { ... }) when the match is the main case and the body is short. - Use the negated guard when the non-matching case is an error or a trivial exit, and the real work follows.
- Do not negate just to avoid an
else. If both branches carry equal weight, the positive form withelseis clearer.
Summary
- A negated pattern swaps which branch gets the binding variable:
!(o instanceof T t)bindstwhen the whole condition is false. - For an
ifwithoutelse, the false-binding is in scope after the statement when the body ends inreturn,throw,breakorcontinue. ||introduces the false-bindings of both operands, so!(o instanceof T t) || t.check()is valid andtis usable on the right.- A binding variable that stays in scope after a guard occupies its name for the rest of the block.
Exercise
Does the following method compile? If not, say why and give the smallest change that fixes it. static int size(Object o) { if (!(o instanceof String s)) { System.out.println("skipping"); } return s.length(); }
Show answer
It does not compile. The body of the if can complete normally (it only prints), so the code after the if can run whether or not the pattern matched, and s is not in scope there. The smallest fix is to make the body exit, for example by adding "return -1;" after the println call. Then s is in scope after the if.
Exercise
Rewrite this method as a guard clause that uses a negated pattern with ||, so the real work is not nested. static String shout(Object o) { if (o instanceof String s && !s.isEmpty()) { return s.toUpperCase() + "!"; } return ""; }
Show answer
static String shout(Object o) { if (!(o instanceof String s) || s.isEmpty()) { return ""; } return s.toUpperCase() + "!"; } The negated pattern is on the left of ||. The right side runs only when the pattern matched, so s is in scope there. When the condition is false, s is bound and remains in scope after the if because the body returns.