Sub topic 7
Negation and Early Returns with `instanceof` Patterns
Prerequisites
This chapter assumes that you know basic Java syntax, reference casts, the instanceof operator, and Boolean operators such as ! and &&. You should also know that a type pattern can declare a variable while testing an object:
if (value instanceof String text) {
System.out.println(text.length());
}Here, text is available inside the if body when value is a String.
The problem with a negative test
A common method needs to reject values of the wrong type and continue only with values of the right type. The traditional form often adds nesting:
static int lengthOrMinusOne(Object value) {
if (value instanceof String) {
String text = (String) value;
return text.length();
}
return -1;
}A type pattern removes the repeated type and cast. However, the most useful form often puts the pattern inside a negated condition:
static int lengthOrMinusOne(Object value) {
if (!(value instanceof String text)) {
return -1;
}
return text.length();
}The condition means “the value is not a String.” If that condition is true, the method returns immediately. Therefore, execution reaches return text.length() only when the pattern matched.
The compiler uses this control-flow fact to make text available after the if statement.
How early return affects scope
An early return is a return statement used before the main work of a method. It exits the method immediately when a guard condition is true.
For a negated type pattern, the variable is in scope after the if when every path through the if that reaches the next statement has matched the pattern:
public final class StringLength {
static int lengthOrMinusOne(Object value) {
if (!(value instanceof String text)) {
return -1;
}
return text.length();
}
public static void main(String[] args) {
System.out.println(lengthOrMinusOne("hello")); // 5
System.out.println(lengthOrMinusOne(42)); // -1
}
}If value is null, value instanceof String text is false. The negation becomes true, so the method returns -1. The method never tries to call a method on null.
Comparing equivalent structures
These two methods have the same behavior:
static int nestedLength(Object value) {
if (value instanceof String text) {
return text.length();
}
return -1;
}
static int guardedLength(Object value) {
if (!(value instanceof String text)) {
return -1;
}
return text.length();
}The guarded form is useful when the method has several operations after the type check. It keeps the successful path unindented and makes the required type clear near the start.
A flow view
Common mistakes
Do not use the binding variable in the rejecting branch:
static int invalidExample(Object value) {
if (!(value instanceof String text)) {
// text is not in scope here.
return -1;
}
return text.length();
}Also remember that removing the early exit changes what the compiler can prove:
static int doesNotCompile(Object value) {
if (!(value instanceof String text)) {
System.out.println("Not a string");
}
// text is not in scope here because this path can continue.
return text.length();
}The if body can finish normally, so execution may reach the final line without a successful match.
Exercise
Rewrite a method named firstCharacter so that it returns the first character of a String value and '\0' for every other object, using a negated type pattern and an early return.
Show answer
static char firstCharacter(Object value) { if (!(value instanceof String text)) { return '\0'; } return text.charAt(0); }