Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
instanceof Keyword in Java
Next article icon

instanceof Keyword in Java

Last Updated : 06 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, instanceof is a keyword used for checking if a reference variable contains a given type of object reference or not. Following is a Java program to show different behaviors of instanceof. Henceforth it is known as a comparison operator where the instance is getting compared to type returning boolean true or false as in Java we do not have 0 and 1 boolean return types.

Example of the Java instanceof Keyword

Java
// Java Program to Illustrate instanceof Keyword  // Importing required I/O classes import java.io.*;  // Main class class GFG {     public static void main(String[] args)     {          // Creating object of class inside main()         GFG object = new GFG();          // Returning instanceof         System.out.println(object instanceof GFG);     } } 

Output
true

Examples of Java instaceof keyword

Here are all the examples of instanceof keywords with their respective cases:

1. Here we will be creating sample classes with a parent-child relationship.

Java
// Java program to demonstrate working of instanceof Keyword  // Class 1 // Parent class class Parent { }  // Class 2 // Child class class Child extends Parent { }  // Class 3 // Main class class GFG {      // Main driver method     public static void main(String[] args)     {          // Creating object of child class         Child cobj = new Child();          // A simple case         if (cobj instanceof Child)             System.out.println("cobj is instance of Child");         else             System.out.println(                 "cobj is NOT instance of Child");          // instanceof returning true for Parent class also         if (cobj instanceof Parent)             System.out.println(                 "cobj is instance of Parent");         else             System.out.println(                 "cobj is NOT instance of Parent");          // instanceof returns true for all ancestors          // Note : Object is ancestor of all classes in Java         if (cobj instanceof Object)             System.out.println(                 "cobj is instance of Object");         else             System.out.println(                 "cobj is NOT instance of Object");     } } 

Output
cobj is instance of Child cobj is instance of Parent cobj is instance of Object

2. instanceof returning false for null 

Java
// Java program to demonstrate that instanceof // returns false for null  class Test { }  class Main {     public static void main(String[] args)     {         Test tobj = null;          // A simple case         if (tobj instanceof Test)             System.out.println("tobj is instance of Test");         else             System.out.println(                 "tobj is NOT instance of Test");     } } 

Output
tobj is NOT instance of Test

3. Parent object is not an instance of Child  

Java
// A Java program to show that a parent object is // not an instance of Child  class Parent { } class Child extends Parent { }  // Driver Class class Test {     // main function     public static void main(String[] args)     {         Parent pobj = new Parent();         if (pobj instanceof Child)             System.out.println("pobj is instance of Child");         else             System.out.println(                 "pobj is NOT instance of Child");     } } 

Output
pobj is NOT instance of Child

4. Parent reference referring to a Child is an instance of a Child

Java
// A Java program to show that a parent reference // referring to a Child is an instance of Child  class Parent { } class Child extends Parent { }  // Driver class class Test {     // main function     public static void main(String[] args)     {         // Reference is Parent type but object is         // of child type.         Parent cobj = new Child();         if (cobj instanceof Child)             System.out.println("cobj is instance of Child");         else             System.out.println(                 "cobj is NOT instance of Child");     } } 

Output
cobj is instance of Child

Application of Java instanceof keyword

We have seen here that a parent class data member is accessed when a reference of parent type refers to a child object. We can access child data members using typecasting. 

Syntax

((child_class_name) Parent_Reference_variable).func.name()

When we do typecasting, it is always a good idea to check if the typecasting is valid or not. instanceof helps us here. We can always first check for validity using instanceof, then do typecasting.

 Example

Java
// Java program to demonstrate that non-method // members are accessed according to reference // type (Unlike methods which are accessed according // to the referred object)  class Parent {     int value = 1000; }  class Child extends Parent {     int value = 10; }  // Driver class class Test {     public static void main(String[] args)     {         Parent cobj = new Child();         Parent par = cobj;          // Using instanceof to make sure that par         // is a valid reference before typecasting         if (par instanceof Child) {             System.out.println(                 "Value accessed through "                 + "parent reference with typecasting is "                 + ((Child)par).value);         }     } } 

Output
Value accessed through parent reference with typecasting is 10


Next Article
instanceof Keyword in Java

T

Twinkle Tyagi
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Instance Methods in Java
    Instance Methods are the group of codes that performs a particular task. Sometimes the program grows in size, and we want to separate the logic of the main method from other methods. A method is a function written inside the class. Since java is an object-oriented programming language, we need to wr
    5 min read
    Important Keywords in Java
    Keywords refer to the reserved set of words of a language. These are used for some predefined actions. abstract: It is a non-access modifier applicable for classes and methods. It is used to achieve abstraction. For more, refer to abstract keyword in javaenum: It is used to define enum in Javainstan
    2 min read
    Record Pattern with instanceof in Java 19
    In Java, the instanceof operator is used to check whether an object is an instance of a particular class or interface. It returns a boolean value of true if the object is an instance of the specified class or interface, and false otherwise. Example of using instanceof Java public class Example { pub
    3 min read
    abstract keyword in java
    In Java, abstract is a non-access modifier in java applicable for classes, and methods but not variables. It is used to achieve abstraction which is one of the pillars of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Characteristics of Java Ab
    7 min read
    var keyword in Java
    The var reserved type name (not a Java keyword) was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it. 1. We can decl
    4 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences