Java Instanceof Operator
Java Instanceof Operator
That means, this operator gives the boolean values such as true or false. If it
relates to a specific class, then it returns true as output. Otherwise, it returns false
as output.
Syntax:
object-reference instanceof type;
student.java
{
public static void main( String args[ ] )
{
// declaring an object 's' of the student class
student s = new student( ) ;
// checking whether s is an instance of the student class using instanceof
operator
Boolean str = s instanceof student;
// printing the string value
System.out.println( str ) ;
}
}
Output:
true
An object of subclass type is also a type of parent class. For example, if a 'student'
class extends the 'Teacher' class, then object of student class can be referred by
either the student class itself or Teacher class. Let us consider the following
example to understand this point more clearly.
Let's see another example.
Student.java
class Teacher { }
public class Student extends Teacher
{
public static void main( String args[ ] )
{
// declaring the object of the class 'Student'
Student s = new Student( ) ;
// checking whether the object s is the instance of the parent class ' Teacher '
Boolean str = s instanceof Teacher ;
// printing the boolean value
System.out.println( str ) ;
}
}
Output:
true
Student.java
// checking whether the s object with null value is the instance of the Student
class
Boolean str = s instanceof Student ;
Student.java
class Teacher { }
public class Student extends Teacher {
static void method( Teacher T )
{
// checking if T (instance of Teacher class) is the instance of Student class
if( T instanceof Student )
{
// performing downcasting
Student s = ( Student ) T ;
System.out.println( " Cool! Downcasting successfully performed! " ) ;
}
}
public static void main ( String [] args )
{
// crating object of class 'Teacher'
Teacher T = new Student( ) ;
Student.method( T ) ;
}
}
Output:
Cool! Downcasting successfully performed!
Student.java
class Teacher { }
public class Student extends Teacher
{
static void method( Teacher T )
{
// performing downcasting
Student s = ( Student ) T ;
System.out.println( " Cool! Downcasting successfully performed! " ) ;
}
Temp1.java