InstanceOf Operator in Java

Java instanceof keyword is used to check whether an object is of a class type or not. If the instanceof operator returns true, then the object can be assigned to the class variable.

Syntax

object instanceof classname

In the above code, the object is verified as the specified class type or not.If the object belongs to the class then it returns true, otherwise it returns false.

Example

car instanceof Vehicle


Program using InstanceOf Operator

package com.yawintutor;

public class InstanceOfOperator {
	public static void main(String[] args) { 
		String  animalName = "Dog";

		System.out.println("Animal name is " + animalName);

		boolean flag = false;
		flag = animalName instanceof String;
		System.out.println("\nIs animal name String? " );
		System.out.println(flag);

	}
}

Output

Animal name is Dog

Is animal name String? 
true


Program using InstanceOf Operator with Customized Objects

In the example below, InstanceOf operator is used to verify customized Objects.

package com.yawintutor;

class ParentClass {  } 
class Child1Class extends ParentClass { } 
class Child2Class extends ParentClass { } 

public class InstanceOfOperator2 {
	
	public static void main(String[] args) { 
		ParentClass child1 = new Child1Class();


		boolean flag = false;
		flag = child1 instanceof Child1Class;
		System.out.println();
		System.out.println("Is child1 is instance of Child1Class? " );
		System.out.println(flag);
		
		flag = child1 instanceof Child2Class;
		System.out.println();
		System.out.println("Is child2 is instance of Child2Class? " );
		System.out.println(flag);

	}
	
	
}

Output

Is child1 is instance of Child1Class? 
true

Is child2 is instance of Child2Class? 
false


Program using InstanceOf Operator with Array

Java array can be verified using instanceof operator. The below example shows how to use instanceof operator with Java array

package com.yawintutor;

public class InstanceOfOperator3 {
	public static void main(String[] args) { 
		String[]  nameArray = {"Dog","Cat"};

		System.out.println("Name Array is " + nameArray);

		boolean flag = false;
		flag = nameArray instanceof String[];
		System.out.println();
		System.out.println("Is nameArray a instance of String Array?" );
		System.out.println(flag);

	}
}

Output

Name Array is [Ljava.lang.String;@34ce8af7

Is nameArray a instance of String Array?
true



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *