- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
java: Class.isInstance vs Class.isAssignableFrom
Let clazz be some Class and obj be some Object .
always the same as
If not, what are the differences?

- 31 if obj == null, the second returns false, the first does not. ;) – Peter Lawrey Oct 19, 2010 at 19:07
- 23 @PeterLawrey, the first will throw a NullPointerException if obj == null . – ryvantage Jan 9, 2014 at 22:40
- Found some answer with samples from hrere : mytechnotes.biz/2012/07/… – Paramesh Korrakuti Oct 19, 2015 at 9:08
- 4 To the readers: you are about to enter a deep, dark, black hole from which you will never escape. The differences are endless. Give up now while you still can: stackoverflow.com/q/496928/1599699 – Andrew Oct 17, 2017 at 12:26
- @ParameshKorrakuti the domain name is changing to tshikatshikaaa.blogspot.com/2012/07/… – Jérôme Verstrynge Feb 9, 2020 at 18:59
4 Answers 4
clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo .
clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz .
is always true so long as clazz and obj are nonnull.
- 4 this misses the case where the Foo is the same as clazz - in which case it returns true: Pauls top-voted answer below corrects this – Rhubarb Mar 21, 2013 at 14:18
- 3 I agree that when clazz is a Foo, then clazz.isAssignableFrom(Foo.class) is true. Where did I say otherwise? – uckelman Apr 2, 2013 at 9:09
- 6 @Gili This isn't what uckelman said. Please re-read his answer. – Puce Mar 3, 2014 at 11:03
- 2 Byte b = 3; Comparable.class.isAssignableFrom(b.getClass()) == Comparable.class.isInstance(b)); -> it's true also for interfaces. – Puce Mar 3, 2014 at 11:05
- 1 Technicality: If obj is null then clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj) will throw a NullPointerException and not return true . – Andrew Macheret Apr 23, 2018 at 22:14
Both answers are in the ballpark but neither is a complete answer.
MyClass.class.isInstance(obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException . In other words, obj is an instance of MyClass or its subclasses.
MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, Other . Other can be a class or an interface. It answers true if Other can be converted to a MyClass .
A little code to demonstrate:
- 10 Why in your example "b isAssignableFrom a:" but code is A.class.isAssignableFrom(B.class) ? I confused by output :) – Roman Truba Jan 30, 2014 at 11:45
- 4 ummm... in all your examples "instanceOf" returns true iff "isAssignableFrom" returns true... I don't see the difference this way. – android developer May 5, 2014 at 18:46
- 3 Be careful the text printed out doesn't match the code and can be confusing ... Example: "System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class));" – polster Apr 1, 2015 at 21:06
- 24 @Paul The answer, as is, is not helpful, because the reader is left wondering "what is the difference between an object being an instance of a subclass of a class and the object's type being convertible to the class?" Surely, you can see that you've left the reader with as many questions after reading your answer as he had when arriving at this page. A better answer would actually explain the difference (or lack thereof). If there is no difference, the answer should directly state, "there is no practical difference." – Aleksandr Dubinsky Feb 10, 2016 at 11:34
- 3 More importantly, the reader is left wondering what the heck to use for their purposes. According to the comments in the question, isAssignableFrom() throws a NullPointerException if the object is null, whereas isInstance() just returns false. That's the real answer. – Andrew Oct 17, 2017 at 12:14
I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance but just the Class object to use isAssignableFrom .
- This isn't 100% true. Comparable.class.isAssignableFrom(Byte.class) == true but Byte.class.isInstance(Comparable.class) == false . In other words, isInstance() is not symmetric for interfaces, only for subclasses. – Gili Feb 28, 2014 at 5:56
- 9 @Gili: You've got it a bit wrong there. Byte.class.isInstance(Comparable.class) is false because a Class object is not an instance of Byte . The correct comparison to Comparable.class.isAssignableFrom(Byte.class) is Comparable.class.isInstance((byte) 1) , which is true. – ColinD Feb 28, 2014 at 17:17
- 1 I disagree. If you look up the Javadoc of Byte you will discover it extends Number and is a class. (byte) 1 is not equivalent to Byte . The former is a primitive. The latter is a Class. – Gili Feb 28, 2014 at 22:11
- 2 @Gili: Autoboxing casts primitive byte to Byte because the parameter type of isInstance is Object . – ColinD Feb 28, 2014 at 22:13
- 2 Okay. My original point was that the calls are not exactly symmetric to each other, but having re-read your answer you never made this assertion so you're right. – Gili Mar 2, 2014 at 16:28
For brevity, we can understand these two APIs like below:
- X.class.isAssignableFrom(Y.class)
If X and Y are the same class, or X is Y 's super class or super interface, return true, otherwise, false.
- X.class.isInstance(y)
Say y is an instance of class Y , if X and Y are the same class, or X is Y 's super class or super interface, return true, otherwise, false.
- So you are saying isAssignableFrom takes class and isInstance takes instance. That is the only difference? – Varun May 24, 2022 at 6:03
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .
Not the answer you're looking for? Browse other questions tagged java or ask your own question .
- The Overflow Blog
- How to use marketing techniques to build a better resume
- How the creator of Angular is dehydrating the web (Ep. 574)
- Featured on Meta
- AI/ML Tool examples part 3 - Title-Drafting Assistant
- We are graduating the updated button styling for vote arrows
- Temporary policy: ChatGPT is banned
- The [connect] tag is being burninated
- Stack Overflow will be testing a title-drafting assistant, and we’d like your...
- We are graduating the "Related questions using Machine Learning" experiment
Hot Network Questions
- Is a written music theory exam noisy?
- Can you be fired for refusing to lie?
- "Error: Too many open files" while starting service in environment with several LXCs
- Does Intelligent Design (ID) entail an infinite regress of designers, and if so, is that problematic?
- How can the US deny access to G7 markets?
- Why would I use \dimexpr .. \relax in \setlength?
- Does the assumption that all known facts are already priced into the share price assume that most participants of the stock market are well-informed?
- Can you exit the Depths without fast travel?
- How can I fix a MacBook that won't start due to a faulty battery? Can I run it without one?
- Is there anything important to know about flying at ~9000ft for the first time?
- What is the basic difference between curry powder and garam masala?
- international space station small White device with LCD and 10keys
- Making a geodesic polyhedron with spheres on the vertices
- Collaborator remade all the figures of our results. How to proceed?
- How can melee attackers do damage if they can't end their turn in someone else's space?
- Have I fried my alternator through frequent use of an external charger?
- Is a parabola really a conic section?
- How do space probes find their way and how much fuel do they use to travel?
- Must a strong reducing agent be a weak oxidising agent, and vice versa?
- SQL Server BACKUP FULL by variables
- Is colour alone enough to convey warning?
- Word for an intentionally high bid on a job
- How could I add fire-like lighting to Rivendell?
- How many sorting networks?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Learn Java interactively.
Learn Java practically and Get Certified .
Popular Tutorials
Popular examples, reference materials.
Learn Java Interactively
Java Introduction
- Java Hello World
- Java JVM, JRE and JDK
- Java Variables and Literals
- Java Data Types
Java Operators
- Java Input and Output
- Java Expressions & Blocks
- Java Comment
Java Flow Control
- Java if...else
- Java switch Statement
- Java for Loop
- Java for-each Loop
- Java while Loop
- Java break Statement
- Java continue Statement
- Java Arrays
- Multidimensional Array
- Java Copy Array
Java OOP (I)
- Java Class and Objects
- Java Methods
- Java Method Overloading
- Java Constructor
- Java Strings
- Java Access Modifiers
- Java this keyword
- Java final keyword
- Java Recursion
Java instanceof Operator
Java oop (ii).
Java Inheritance
Java Method Overriding
- Java super Keyword
- Abstract Class & Method
- Java Interfaces
- Java Polymorphism
- Java Encapsulation
Java OOP (III)
- Nested & Inner Class
- Java Static Class
- Java Anonymous Class
- Java Singleton
- Java enum Class
- Java enum Constructor
- Java enum String
- Java Reflection
- Java Exception Handling
- Java Exceptions
- Java try...catch
- Java throw and throws
- Java catch Multiple Exceptions
- Java try-with-resources
- Java Annotations
- Java Annotation Types
- Java Logging
- Java Assertions
- Java Collections Framework
- Java Collection Interface
- Java List Interface
- Java ArrayList
- Java Vector
- Java Queue Interface
- Java PriorityQueue
- Java Deque Interface
- Java LinkedList
- Java ArrayDeque
- Java BlockingQueue Interface
- Java ArrayBlockingQueue
- Java LinkedBlockingQueue
- Java Map Interface
- Java HashMap
- Java LinkedHashMap
- Java WeakHashMap
- Java EnumMap
- Java SortedMap Interface
- Java NavigableMap Interface
- Java TreeMap
- Java ConcurrentMap Interface
- Java ConcurrentHashMap
- Java Set Interface
- Java HashSet
- Java EnumSet
- Java LinkedhashSet
- Java SortedSet Interface
- Java NavigableSet Interface
- Java TreeSet
- Java Algorithms
- Java Iterator
- Java ListIterator
- Java I/O Streams
- Java InputStream
- Java OutputStream
- Java FileInputStream
- Java FileOutputStream
- Java ByteArrayInputStream
- Java ByteArrayOutputStream
- Java ObjectInputStream
- Java ObjectOutputStream
- Java BufferedInputStream
- Java BufferedOutputStream
- Java PrintStream
Java Reader/Writer
- Java Reader
- Java Writer
- Java InputStreamReader
- Java OutputStreamWriter
- Java FileReader
- Java FileWriter
- Java BufferedReader
- Java BufferedWriter
- Java StringReader
- Java StringWriter
- Java PrintWriter
Additional Topics
- Java Scanner Class
- Java Type Casting
- Java autoboxing and unboxing
- Java Lambda Expression
- Java Generics
- Java File Class
- Java Wrapper Class
- Java Command Line Arguments
Java Tutorials
- Java Nested Static Class
- Java Abstract Class and Abstract Methods
In this tutorial, you will learn about Java instanceof operator in detail with the help of examples.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.
Its syntax is
Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
Example: Java instanceof
In the above example, we have created a variable name of the String type and an object obj of the Main class.
Here, we have used the instanceof operator to check whether name and obj are instances of the String and Main class respectively. And, the operator returns true in both cases.
Note : In Java, String is a class rather than a primitive data type. To learn more, visit Java String .
- Java instanceof during Inheritance
We can use the instanceof operator to check if objects of the subclass is also an instance of the superclass. For example,
In the above example, we have created a subclass Dog that inherits from the superclass Animal . We have created an object d1 of the Dog class.
Inside the print statement, notice the expression,
Here, we are using the instanceof operator to check whether d1 is also an instance of the superclass Animal .
- Java instanceof in Interface
The instanceof operator is also used to check whether an object of a class is also an instance of the interface implemented by the class. For example,
In the above example, the Dog class implements the Animal interface. Inside the print statement, notice the expression,
Here, d1 is an instance of Dog class. The instanceof operator checks if d1 is also an instance of the interface Animal .
Note : In Java, all the classes are inherited from the Object class. So, instances of all the classes are also an instance of the Object class.
In the previous example, if we check,
The result will be true .
Table of Contents
- Java instanceof
- Example: instanceof
Sorry about that.
Related Tutorials
Java Tutorial
Try PRO for FREE
Todd Ginsberg
Coming in Java 16: Pattern Matching for instanceof
A deceptively simple feature covers quite a few interesting use cases
In this post, we’ll go over a new feature coming to Java 16 that brings a lot of change, despite how simple it might look at first glance.
Historically when we’ve used the instanceof operator, it’s been up to the developer to perform the inevitable cast when the type check is true. Starting in Java 16, we’ll be able to let Java perform the cast for us! This feature was in preview for Java 14 and Java 15 and will be officially released in Java 16 (meaning we can use it without having to opt-in via a compiler flag).
The Main Use Case - Before Java 16
First, let’s go over how we check the type of an object and then use that object without the new feature.
In this specific case, we check to make sure that someObject is an instance of String , and if it is, we manually cast someObject to a String , and put it in a new local variable called someString . That works fine, and if you’ve been using Java for a while, you’ve probably written something like this yourself, or have run into code that does this.
This cast is commonly the very first thing done after the instanceof check, so why not optimize the syntax around that a bit?
Now With Pattern Matching
Now we can define a local variable ( someString ) that is automatically cast to the type we’re checking against ( String ) if and only if the instanceof check is true.
How great is that? We’ve avoided that ugly manual cast when performing a type check!
There are a couple of scoping rules to keep in mind when working with type patterns. First, someString in this case is only in scope for the if block. Once we reach the end of that block, we can’t refer to someString any more.
The second thing to keep in mind is that the variable we define is essentially a local variable. This means we can’t shadow another variable of the same name in the local scope. For example:
In that case we can’t shadow our local someString with another someString defined in our pattern match. We can, however, shadow a field in our class:
These scoping rules initially struck me as a bit counterintuitive but since I try not to shadow variables, I figure I’ll get used to it.
That Seems Simple. Is That It?
No! We can do all sorts of things with patern matching for instanceof.
For example, since someString is now defined, we can write conditional tests against it without having to define another nested if statement. In this case, checking that our String starts with “Awesome”:
If all we wanted to do was to test that someObject is a String that starts with “Awesome”, we could write that like this, again taking advantage of pattern matching.
This is a much simpler version of what we would have had to do before, where we would have had an ugly manual cast:
Think of how much nicer our equals methods are going to look! Let’s rewrite the equals method on java.lang.Integer :
What a difference! Now the code is concise and intuitive.
What’s Next?
There is talk about extending pattern matching to switches (both statements and expressions) and to destructuring record classes (a nice feature in Kotlin with data classes). Those all sound pretty exciting, but I’d settle for being able to negate instanceof directly - !instanceof intead of !(t instanceOf S)
Do you have a place in your code where you think pattern matching for instanceof will come in handy? Let me know!
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
Equality, Relational, and Conditional Operators
The equality and relational operators.
The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use " == ", not " = ", when testing if two primitive values are equal.
The following program, ComparisonDemo , tests the comparison operators:
The Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
The following program, ConditionalDemo1 , tests these operators:
Another conditional operator is ?: , which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true , assign the value of value1 to result . Otherwise, assign the value of value2 to result ."
The following program, ConditionalDemo2 , tests the ?: operator:
Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).

The Type Comparison Operator instanceof
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
The following program, InstanceofDemo , defines a parent class (named Parent ), a simple interface (named MyInterface ), and a child class (named Child ) that inherits from the parent and implements the interface.
When using the instanceof operator, keep in mind that null is not an instance of anything.
About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights
Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.
Java Tutorial
Java methods, java classes, java file handling, java how to, java reference, java examples, java instanceof keyword.
❮ Java Keywords
Check whether an object is an instance of a specific class:
Try it Yourself »
Definition and Usage
The instanceof keyword checks whether an object is an instance of a specific class or an interface.
The instanceof keyword compares the instance with type. The return value is either true or false .
Related Pages
Read more about objects in our Java Classes/Objects Tutorial .

COLOR PICKER

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, get certified.
- Android App Development (Live)
- Data Science (Live)
- DSA for Interview Preparation
- DSA Live for Working Professionals
- DSA Self-paced in C++/Java
- DSA Self-paced in Python
- DSA Self-paced in Javascript
- DSA Self-paced in C
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Data Structures & Algorithms in JavaScript
- Explore More Live Courses
- Interview Preparation Course
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Generic Tree
- Binary Tree
- Binary Search Tree
- Red Black Tree
- All Tree Data Structures
- Advanced Data Structure
- All Data Structures
- Design and Analysis of Algorithms
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Linear Search
- Binary Search
- All Searching Algorithms
- Selection Sort
- Bubble Sort
- Insertion Sort
- Counting Sort
- Bucket Sort
- All Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Backtracking
- Divide and Conquer
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- All Algorithms
- What is System Design
- Monolithic and Distributed SD
- Scalability in SD
- Databases in SD
- High Level Design or HLD
- Low Level Design or LLD
- Complete System Design Tutorial
- Factory Pattern
- Observer Pattern
- Singleton Design Pattern
- Decorator Pattern
- Strategy Pattern
- Adapter Pattern
- Command Pattern
- Iterator Pattern
- Prototype Design Pattern
- All Design Patterns
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Multiple Choice Quizzes
- Aptitude for Placements
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 12 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 SS Syllabus
- Class 8 SS Syllabus
- Class 9 SS Syllabus
- Class 10 SS Syllabus
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Political Science
- Machine Learning
- Data Science
- Microsoft Azure Tutorial
- Google Cloud Platform
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- Geography Notes
- Modern Indian History Notes
- Medieval Indian History Notes
- Ancient Indian History Notes
- Complete History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- Government Schemes (Updated)
- UPSC Previous Year Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Corporate Hiring Solutions
- Apply through Jobathon
- Apply for a Job
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
Related Articles
- Write an Interview Experience
- Write an Admission Experience
- new Operator vs newInstance() Method in Java
instanceof operator vs isInstance() Method in Java
- Class isInstance() method in Java with Examples
- Throwable getStackTrace() method in Java with Examples
- Throwable printStackTrace() method in Java with Examples
- Different Ways to Print Exception Messages in Java
- throw and throws in Java
- User-defined Custom Exception in Java
- Infinity or Exception in Java when divide by 0?
- Java Multiple Catch Block
- Chained Exceptions in Java
- Null Pointer Exception In Java
- Output of Java program | Set 12(Exception Handling)
- Java | Exception Handling | Question 1
- Java | Exception Handling | Question 2
- Java | Exception Handling | Question 3
- Java | Exception Handling | Question 4
- Java | Exception Handling | Question 8
- Java | Exception Handling | Question 6
- Java | Exception Handling | Question 7
- Nested try blocks in Exception Handling in Java
- Flow control in try catch finally in Java
- Types of Exception in Java with Examples
- Checked vs Unchecked Exceptions in Java
- Arrays in Java
- Spring Boot - Start/Stop a Kafka Listener Dynamically
- Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
- Split() String method in Java with examples
- Arrays.sort() in Java with examples
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.
The instanceof operator and isInstance() method both return a boolean value. isInstance() method is a method of class Class in java while instanceof is an operator.
Consider an Example:
Output:
Now if we want to check the class of the object at run time, then we must use isInstance() method.
Note: instanceof operator throws compile-time error(Incompatible conditional operand types) if we check object with other classes which it doesn’t instantiate.
Output :
- new operator vs newInstance() method in Java
- Reflections in Java
This article is contributed by Gaurav Miglani . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...
- nishkarshgandhi

Master Java Programming - Complete Beginner to Advanced

JAVA Backend Development - Live

Data Structures and Algorithms - Self Paced
Improve your coding skills with practice.

Java Object Class
Java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week


IMAGES
VIDEO
COMMENTS
In other words, instanceof operator checks if the left object is same or subclass of right class, while isAssignableFrom checks if we can assign object of the parameter class (from) to the reference of the class on which the method is called. Note that both of these consider the actual instance not the reference type.
MyClass.class.isInstance (obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException. In other words, obj is an instance of MyClass or its subclasses. MyClass.class.isAssignableFrom (Other.class) will return true if MyClass is the same as, or a superclass ...
In a compiled class file, they utilize different opcodes: The instanceof keyword corresponds to the instanceof opcode. Both the isInstance and isAssignableFrom methods will use the invokevirtual opcode. In the JVM Instruction Set, the instanceof opcode has a value of 193, and it has a two-byte operand: instanceof indexbyte1 indexbyte2.
1. Overview. In this quick tutorial, we'll continue our series on Java 14 by taking a look at Pattern Matching for instanceof which is another new preview feature included with this version of the JDK. In summary, JEP 305 aims to make the conditional extraction of components from objects much simpler, concise, readable and secure.
A destructuring, extracting either the length and width or the radius from the Shape object. Pattern matching enables you to remove the conversion step by changing the second operand of the instanceof operator with a type pattern, making your code shorter and easier to read: public static double getPerimeter (Shape shape) throws ...
The instanceof operator is also used to check whether an object of a class is also an instance of the interface implemented by the class. For example, In the above example, the Dog class implements the Animal interface. Inside the print statement, notice the expression, Here, d1 is an instance of Dog class. The instanceof operator checks if d1 ...
2021-01-12 Todd Ginsberg. In this post, we'll go over a new feature coming to Java 16 that brings a lot of change, despite how simple it might look at first glance. Historically when we've used the instanceof operator, it's been up to the developer to perform the inevitable cast when the type check is true. Starting in Java 16, we'll be ...
This beginner Java tutorial describes fundamentals of programming in the Java programming language ... this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result." The following program ... The instanceof operator compares an object to a specified type. You ...
Definition and Usage. The instanceof keyword checks whether an object is an instance of a specific class or an interface. The instanceof keyword compares the instance with type. The return value is either true or false. Read more about objects in our Java Classes/Objects Tutorial. Java Keywords.
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used. The instanceof operator and isInstance () method both return a boolean ...
The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).. The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.