Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

Which of the following is better?

a instanceof B

or

B.class.isAssignableFrom(a.getClass())

The only difference that I know of is, when 'a' is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result?

1 Answer

0 votes
by (46k points)

While applying instanceof, you require to apprehend the class of B at compile-time and instanceof can solely be applied with reference types, not primitive types. 

While using isAssignableFrom() it can be powerful and vary during runtime and isAssignableFrom() can be done with any class objects:

To learn more click here.

Related questions

Browse Categories

...