Sub topic 4
What a binding variable is
This chapter assumes you know basic Java syntax and classes, inheritance and subtyping, the instanceof operator with reference casts, and the boolean operators &&, || and !. It also assumes you have seen an equals method. The code needs Java 16 or later.
The declaration inside the test
In the previous chapter you wrote o instanceof String s. The part String s is a type pattern. The name s is a binding variable: a local variable that the pattern declares, and that the compiler assigns only when the test succeeds.
public class BindingBasics {
public static void main(String[] args) {
Object o = "hello";
if (o instanceof String s) {
System.out.println(s.length());
}
}
}When this runs, the program does three things in order:
- It evaluates
oand checks that the value is notnulland is an instance ofString. - If so, it casts the reference to
String. - It stores the result in
sand the wholeinstanceofexpression evaluates totrue.
If the check fails, s is never assigned, and the expression evaluates to false. The compiler tracks this. You can only read s in places where the match is guaranteed to have succeeded, which is the subject of the next chapter.
The type of a binding variable
The type of a binding variable is the type written in the pattern. It is not the type of the expression on the left, and it is not necessarily the runtime class of the object.
import java.util.List;
public class BindingType {
public static void main(String[] args) {
Object o = "hello";
if (o instanceof CharSequence cs) {
// cs has static type CharSequence, although the object is a String.
System.out.println(cs.length());
System.out.println(cs.charAt(0));
// System.out.println(cs.isBlank()); // does not compile: not a CharSequence method
}
Object list = List.of(1, 2, 3);
if (list instanceof List<?> l) {
System.out.println(l.size());
}
}
}Here the runtime class of o is String, but cs only offers the methods of CharSequence. This is the same rule as an ordinary cast, CharSequence cs = (CharSequence) o;. The pattern chooses the view you get. To call String-only methods, write String s in the pattern.
The binding variable refers to the same object as the left operand. Nothing is copied, so s == o is true after a match.
What the compiler does with it
The compiler turns the pattern into the old idiom. The following two methods behave the same way, and they compile to nearly the same bytecode.
public class Desugared {
static int lengthOld(Object o) {
if (o instanceof String) {
String s = (String) o;
return s.length();
}
return -1;
}
static int lengthNew(Object o) {
if (o instanceof String s) {
return s.length();
}
return -1;
}
public static void main(String[] args) {
System.out.println(lengthOld("abc"));
System.out.println(lengthNew("abc"));
System.out.println(lengthNew(42));
}
}The output is 3, 3, -1. The new form has no performance advantage. Its benefit is that the type name appears once and the variable cannot be used before the type check.
A binding variable is an ordinary local variable
Apart from how it is declared, a binding variable behaves like any other local variable. These points follow from that.
It can be reassigned
Since Java 16, binding variables are not implicitly final. You may assign to them.
public class Reassign {
public static void main(String[] args) {
Object o = " padded ";
if (o instanceof String s) {
s = s.strip();
System.out.println("[" + s + "]");
}
}
}This prints [padded]. Reassigning a binding variable is legal, but it can mislead a reader who assumes the name still holds the tested value. It also affects scope rules later, because the compiler uses the fact that a binding variable is never reassigned in some situations.
It can be declared `final`
If you want to forbid reassignment, put the modifier in the pattern.
public class FinalBinding {
public static void main(String[] args) {
Object o = "text";
if (o instanceof final String s) {
// s = "other"; // does not compile: cannot assign a value to final variable s
System.out.println(s);
}
}
}It cannot reuse the name of a local variable in scope
A binding variable cannot have the same name as a local variable or parameter that is already in scope.
public class NameClash {
static void show(Object o, String s) {
// if (o instanceof String s) { } // does not compile: variable s is already defined
if (o instanceof String t) {
System.out.println(t + s);
}
}
public static void main(String[] args) {
show("a", "b");
}
}It can shadow a field
A field is not a local variable, so a binding variable may share its name. Inside the scope, the simple name refers to the binding variable, and you reach the field with this..
public class FieldShadow {
private final String name = "field";
void show(Object o) {
if (o instanceof String name) {
System.out.println(name); // the binding variable
System.out.println(this.name); // the field
}
}
public static void main(String[] args) {
new FieldShadow().show("binding");
}
}This prints binding and then field. Shadowing is legal, but it makes equals methods and similar code easy to misread, so most style guides prefer a different name.
Which patterns are allowed
The compiler rejects a type pattern when the test could never succeed. This is the same rule as for a cast.
public class Incompatible {
public static void main(String[] args) {
Integer i = 1;
// if (i instanceof String s) { } // does not compile: Integer cannot be cast to String
Object o = i;
if (o instanceof Integer n) {
System.out.println(n + 1);
}
}
}Integer and String are unrelated final classes, so no object can be both. With Object on the left, the test is allowed.
There is one version-dependent rule. When the static type of the left operand is already a subtype of the pattern type, the test can only fail for null. Java 16 through 20 reported a compile error for this case. Java 21 and later accept it. Check your language level if you see an error such as "expression type is a subtype of pattern type".
You also cannot write var as the type in a top-level type pattern. o instanceof var s does not compile, because it would test nothing. Write the type you want.
Binding variables and the old idiom compared
| Property | Cast in the old idiom | Binding variable |
|---|---|---|
| Where the type is written | Twice: in `instanceof` and in the cast | Once, in the pattern |
| Declaration | Separate statement | Part of the test |
| Assigned when | Whenever the cast statement runs | Only when the test succeeds |
| Can be misused before the test | Yes, by moving the cast | No, the compiler checks |
| Can be reassigned | Yes | Yes, unless declared `final` |
| Scope | The enclosing block | Where the match is guaranteed |
The last row is the main difference. A normal local variable is in scope from its declaration to the end of its block. A binding variable's scope depends on the control flow, which the next chapter covers.
Checking your understanding
The following program combines the points from this chapter. Read it and predict the output before running it.
public class Predict {
private final String label = "field";
String describe(Object o) {
if (o instanceof CharSequence label) {
return label.length() + ":" + this.label;
}
return "none";
}
public static void main(String[] args) {
Predict p = new Predict();
System.out.println(p.describe("abcd"));
System.out.println(p.describe(new StringBuilder("xy")));
System.out.println(p.describe(7));
System.out.println(p.describe(null));
}
}The output is 4:field, 2:field, none, none. The binding variable label shadows the field inside the if body, StringBuilder is a CharSequence, and neither 7 nor null matches.
Exercise
In if (o instanceof CharSequence cs) { ... } where o holds the String "abc", what is the static type of cs, and can you call cs.isBlank() inside the block?
Show answer
The static type of cs is CharSequence, the type written in the pattern. isBlank() is declared in String, not in CharSequence, so the call does not compile. To call it, use the pattern String s instead.
Exercise
Which of these lines fails to compile, and why? (a) if (o instanceof String s) { s = s.trim(); } (b) if (o instanceof final String s) { s = s.trim(); } (c) void f(Object o, String s) { if (o instanceof String s) { } }
Show answer
(b) fails because the pattern declares s as final, so it cannot be assigned. (c) fails because a binding variable cannot reuse the name of the parameter s, which is already in scope. (a) compiles in Java 16 and later, because binding variables are not implicitly final.
Exercise
Does o instanceof String s copy the string? After a successful match, what is the result of s == o?
Show answer
It does not copy anything. The binding variable holds the same reference as o, so s == o is true. The cast only changes the static type through which the object is accessed.