Skip to main content

How to Check an Object's Type in Java with instanceof Pattern Matching

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

value instanceof String text tests whether a Java object is a String and, when it is, gives you the object as a String named text, with no cast. The variable exists only where the test is known to be true, which is why instanceof patterns work with && and with an early return, but not with ||.

Syntax​

Syntax
if (value instanceof Type name) {
// here, name is value as a Type
}
PartWhat it does
valueThe variable or expression to test, often of type Object.
instanceof TypeTests whether value is a Type, such as String or Integer. For null, the test is false.
nameThe pattern variable. When the test is true, it holds value converted to Type, so the code uses it without a cast.

Oracle's Java 25 guide, Pattern Matching for instanceof: "Pattern matching with instanceof involves testing whether a target's type matches the type in the pattern. If so, the target is converted to the type in the pattern, and then the pattern variables are automatically initialized with data from the target."

The Example​

The example's describe method takes any Object and says whether it's a String or an Integer, using each pattern variable as its own type. planName turns the test around with ! to leave early when the value isn't a String, and then uses name after the if.

Prerequisites​

  • A JDK 16 or later, which has pattern matching for instanceof and can run a single .java file directly. This guide uses OpenJDK 25.0.5.1.

Step 1: Write the Code​

Create a file named Main.java:

Main.java with a describe method that tests value instanceof String text and value instanceof Integer number, a planName method that returns no plan unless value instanceof String name, and a main method that calls them.

Main.java
public class Main {

static String describe(Object value) {
// If value is a String, it's also available as text, already a String.
if (value instanceof String text) {
return "text with " + text.length() + " characters";
}
if (value instanceof Integer number) {
return "the whole number " + number;
}
return "something else";
}

static String planName(Object value) {
// Leave early when value isn't a String. After this if, name is a String.
if (!(value instanceof String name)) {
return "no plan";
}
return name.toUpperCase();
}

public static void main(String[] args) {
System.out.println(describe("customer"));
System.out.println(describe(500));
System.out.println(describe(2.5));
System.out.println(planName("pro"));
System.out.println(planName(500));
}
}

Step 2: Run It​

Terminal
java Main.java
Output
text with 8 characters
the whole number 500
something else
PRO
no plan

A zsh terminal where java Main.java prints text with 8 characters, the whole number 500, something else, PRO and no plan.

java Main.java compiles the file in memory and runs it. The command is the same in zsh, bash and PowerShell.

What Happened​

  • describe("customer") matched the String pattern, so text held the string, and text.length() gave 8.
  • describe(500) matched the Integer pattern. Passed as an Object, 500 became an Integer object, and number held it.
  • describe(2.5) matched neither. 2.5 became a Double.
  • planName("pro") printed PRO. The negated test was false, so the method didn't return early, and name could be used after the if.
  • planName(500) printed no plan, because 500 isn't a String.

The guide explains why name works after the if: "The scope of a pattern variable can extend beyond the statement that introduced it". When the if always returns, the code after it runs only when the test was true.

Common Mistakes​

MistakeWhat happensDo this instead
Using the pattern variable after an if that doesn't leave earlyerror: cannot find symbol, with symbol: variable textUse it inside the if, or turn the test around and return early, as planName does
Combining the test with ||, as in value instanceof String text || text.isEmpty()error: cannot find symbol: on the right of ||, the test may have been falseUse &&, whose right side runs only when the test was true
A pattern with a type argument, as in value instanceof List<String> listerror: Object cannot be safely cast to List<String>Test with List<?>, and check the elements' types one by one
Expecting every whole number in an Object to be an IntegerA large number can be a Long, and then instanceof Integer is falseTest for Number when any kind of number will do: it was true for both

Troubleshooting​

SymptomLikely causeFix
error: cannot find symbol, with symbol: variable and the pattern variable's nameThe variable is used where the test may have been falseMove the code inside the if, or join it to the test with &&
error: Object cannot be safely cast to List<String>The pattern has a type argument the program can't checkUse List<?>
error: incompatible types: String cannot be converted to IntegerThe variable's type can never be the tested type, such as a String variable tested for IntegerTest a variable of a wider type, such as Object

FAQ​

Is instanceof true for null?​

No. For a variable that holds null, instanceof String was false, so a pattern never matches null, and a pattern variable is never null.

Which Java version added pattern matching for instanceof?​

Java 16, with JEP 394.

Conclusion​

value instanceof Type name checks an object's type and gives you the object as that type in one step. The pattern variable exists only where the test is known to be true: inside the if, after a negated test that returns early, and on the right of &&.

Additional Resources​