instanceof Keyword in Java
Last Updated :
06 Jul, 2023
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);
}
}
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");
}
}
Outputcobj 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");
}
}
Outputtobj 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");
}
}
Outputpobj 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");
}
}
Outputcobj 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);
}
}
}
OutputValue accessed through parent reference with typecasting is 10
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read