Java Keywords (Part XIV): Using the instanceof Operator

We are up to 38 keywords covered in previous articles! That's 79% keywords covered. We have only 10 keywords to cover and I will be covering 1 of those in this article. We are almost done with all the basic keywords. This article will illustrate the use of the keyword instanceof. I suggest you start with Java Keywords (Part I) before proceeding further, if you have not read any of the previous articles in the Java Keyword series. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page. The series was written with natural progression in mind. Therefore, some of the keywords already covered may be used in code examples illustrated here.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

What is the instanceof operator?

This operator performs a comparison operation of an object against a "Type" to determine if a particular object is of that type. As expected, the result of the comparison is a Boolean value. For example:

boolean result = obj instanceof MyClass;
If the variable obj is an instance of the class MyClass, the above snippet will return true. Otherwise, it will return false. Simple enough, right?

Drawbacks of instanceof Operator

This operator returns true if the object being evaluated is an instance of the class to the right of the operator or of any class in the hierarchy chain. Consider this example:

public class Shape {...}

public class Polygon extends Shape {...}

public class Square extends Polygon {...}
If an object of type Square is evaluated using instanceof...
  
public static void main (String[] args) {
	Polygon square = new Square();

	if (square instanceof Shape) {
		System.out.println("I'm a shape"); // This will print out...
	}
		
	if (square instanceof Polygon) {
		System.out.println("I'm a polygon"); // and this...
	}
	
	if (square instanceof Square) {
		System.out.println("I'm a square"); // also this...
	}
	
	if (square.getClass().isAssignableFrom(Polygon.class)) {
		System.out.println("I am assignable from Polygon"); // This won't...
	} else {
		System.out.println("I'm a polygon; just not assignable from it."); // but this will.
	}
}
It will return true for comparisons against Shape, Polygon, and Square, even though the object is not a direct instance of that class.

OUTPUT:

I'm a shape
I'm a polygon
I'm a square
I'm a polygon; just not assignable from it.
For these reasons, you should prefer using over instanceof. That said, as long as you understand the expected behavior of this operation, you should be fine using it. I hope I did a good enough job explaining the ins and outs of it for you to make a good decision when it comes time to use it. If not, let me know in the comments below.

New way for using instanceof operator

Since Java 14 and according to Oracle,
Pattern matching involves testing whether an object has a particular structure, then extracting data from that object if there's a match.
This was already part of Java. For instance, you could evaluate an object to determine whether or not the object is an instance of a particular class, then use typecasting to "convert" the object into an instance of the class it was evaluated against. However, it is simpler to do now. Before, you could do something like this:

if (obj instanceof Square) {
	Square s = (Square) obj; // This is called "typecasting"
    s.someMethodOfSquare();
    ...
}
Now, you can simply do something like this:

if (obj instanceof Square s) {
    s.someMethodOfSquare();
    ...
}
This new way of using instanceof is known as Pattern Matching.

Next up, Part XV: The many uses of the this keyword

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

Customizing Java Records

Exception Handling: File CRUD Operations Example