Sub topic 6
Adding conditions with &&
This chapter assumes you can read a basic type pattern such as o instanceof String s. It also assumes you know that && short-circuits, meaning it skips its right operand when the left one is already false. The patterns here need Java 16 or later.
Why && is the natural partner of a pattern
A type test is rarely the whole question. Usually you want to know whether an object is a String and whether that string is long enough, or non-empty, or equal to something. Before patterns, that meant a cast and a second check:
if (o instanceof String) {
String s = (String) o;
if (s.length() > 10) {
System.out.println(s);
}
}With a type pattern, the same logic fits in one condition:
if (o instanceof String s && s.length() > 10) {
System.out.println(s);
}The binding variable s is declared in the left operand and used in the right operand of the same expression. This works because of how && evaluates. The right side runs only when the left side was true, and the left side is true only when the pattern matched. At that point s is guaranteed to hold a String. The compiler follows this reasoning and lets you use s there.
The rule: in scope where the pattern must have matched
A binding variable is in scope at a place in the code when the compiler can prove the pattern matched on every path that reaches that place. This is called flow scoping. For a && b, the compiler applies these rules:
- Any binding introduced by
awhenais true is in scope inb. - Any binding introduced by
awhenais true is in scope wherever the wholea && bexpression is known to be true. - Bindings introduced by
bare likewise in scope wherevera && bis true.
The last two rules are why the body of an if can use the binding. The body runs only when the whole condition is true, so every pattern in the chain matched.
A complete example
The following program uses && in a return expression, in a chain of two patterns, in a ternary, and in a lambda.
import java.util.List;
public class AndConditions {
static boolean isLongString(Object o) {
return o instanceof String s && s.length() > 10;
}
static String describe(Object a, Object b) {
if (a instanceof String name && b instanceof Integer age && age >= 18) {
return name + " is an adult aged " + age;
}
return "no match";
}
static String label(Object o) {
return o instanceof String s && !s.isBlank() ? s.strip() : "unknown";
}
public static void main(String[] args) {
System.out.println(isLongString("hello")); // false
System.out.println(isLongString("hello, world!")); // true
System.out.println(isLongString(null)); // false
System.out.println(isLongString(42)); // false
System.out.println(describe("Ana", 30)); // Ana is an adult aged 30
System.out.println(describe("Ana", 12)); // no match
System.out.println(describe("Ana", "x")); // no match
System.out.println(label(" padded ")); // padded
System.out.println(label(" ")); // unknown
List<Object> items = List.of("a", "abcd", 7, "hello");
List<Object> longer = items.stream()
.filter(x -> x instanceof String s && s.length() > 3)
.toList();
System.out.println(longer); // [abcd, hello]
}
}Notes on each part:
isLongStringreturnsfalsefornulland for non-strings without any extra checks. A failed pattern makes the left sidefalse, and&&then skips the length call. There is noNullPointerExceptionand noClassCastException.describechains two patterns. The third operand,age >= 18, usesage, which was bound by the second operand. Each operand can use every binding to its left. After theifsucceeds,nameandageare both in scope in the body.labeluses the binding in the "true" branch of the ternary. The conditiono instanceof String s && !s.isBlank()must be true for that branch to run, sosis available there.- The lambda shows that a pattern also works inside an expression-bodied lambda. The binding
slives only inside that one expression.
Order matters
The compiler reads left to right. A binding is available only to operands that come after the pattern that introduces it.
static boolean wrongOrder(Object o) {
// Does not compile: s is used before the pattern that declares it.
// return s.length() > 10 && o instanceof String s;
return o instanceof String s && s.length() > 10;
}The commented-out line fails because the compiler has not seen s by the time it reaches s.length(). Always put the pattern first and the conditions that depend on it after.
This order also protects you at runtime. Because the type test comes first and && short-circuits, the dependent condition never sees a value of the wrong type or null.
Chaining several patterns
You can put as many patterns in one && chain as you need. Each binding needs its own distinct name.
static boolean sameText(Object a, Object b) {
return a instanceof String x
&& b instanceof String y
&& x.equalsIgnoreCase(y);
}If you reuse a name that is already in scope, the compiler rejects it:
static boolean clash(Object a, Object b) {
// Does not compile: s is already defined when the second pattern is declared.
// return a instanceof String s && b instanceof String s && s.isEmpty();
return a instanceof String s1 && b instanceof String s2 && s1.equals(s2);
}Where the binding is not in scope
The binding is in scope only where the whole && chain is known to be true. The common place where this is not the case is the else branch.
static String classify(Object o) {
if (o instanceof String s && s.length() > 3) {
return "long string: " + s;
} else {
// s is not in scope here. This branch also runs when o is a String of length 3 or less.
return "something else";
}
}The else branch runs when the condition is false. That can happen because the pattern failed, or because the pattern matched and the length check failed. The compiler cannot tell which, so s is not available.
A binding also does not leak out of an if that uses &&:
static int after(Object o) {
if (o instanceof String s && s.length() > 3) {
System.out.println(s);
}
// s is not in scope here.
return 0;
}Because the scope of s ends with the if statement, you can reuse the name s in a later, separate if. The exception is the early-exit form covered in the chapter on negation and early returns. There, the binding stays in scope after the if, and reusing the name would clash.
Binding variables are ordinary local variables
A binding variable behaves like a local variable declared in the condition. Two consequences matter when you add conditions:
- It can be reassigned. Unless you write
finalbefore the type (o instanceof final String s), you can assign tosinside the body. Most style guides advise against it, because the reader expectssto still be the matched object. - It can shadow a field. If your class has a field named
s, the binding hides it within the scope. A laterthis.sstill reaches the field. Giving the binding a different name avoids the confusion.
Summary of the && rules
| Position | Is the binding from `x instanceof T t && ...` in scope? |
|---|---|
| Right operand of the same `&&` | Yes |
| Body of an `if` using the whole chain as its condition | Yes |
| "True" branch of a ternary using the chain as its condition | Yes |
| `else` branch of that `if` | No |
| Code after the `if` (with no early exit) | No |
| Left of the pattern in the same expression | No |
Exercises
Exercise
Why does return o instanceof String s && s.length() > 10; return false for null instead of throwing a NullPointerException?
Show answer
instanceof, including with a pattern, is false for null. The left operand of && is therefore false, and && skips the right operand, so s.length() is never called.
Exercise
This method does not compile. Explain why and fix it so it returns true when o is a non-empty String or when o is the Integer 0.
static boolean test(Object o) {
return o instanceof String s || s.length() > 0;
}
Show answer
In a || b, the right side runs when the left side is false, that is, when the pattern did not match, so s is not in scope. A fix is return (o instanceof String s && !s.isEmpty()) || (o instanceof Integer i && i == 0);. Each binding is used only inside the && chain that declares it.
Exercise
In if (a instanceof String x && b instanceof String y && x.length() == y.length()) { ... } else { ... }, which of x and y are in scope in the else branch?
Show answer
Neither. The else branch runs when any one of the three operands was false, so the compiler cannot prove that either pattern matched.