instanceof operator in java

In this article, we will see about instanceof operator in java with example. We will see what the instanceof operator does, how instanceof operator works in case of the interface and also we will see how to use instanceof operator in real time scenario.

  • The instanceof operator checks any reference or object is the type of class or interface or not. It returns true or false.
  • It avoids ClassCastException at runtime.
  • The instanceof operator returns false if we have null as a reference.

instanceof operator in java

 

Example 1 –

package instanofexample;

class Book{
	
}

public class Example1 {
public static void main(String[] args) {
	
	Book b = new Book();
	
	if(b instanceof Book) {
		System.out.println("b is type of book");
	}
		
}
}

Output is – b is type of book

 

Example 2 -In this example, we will see why exactly we need instanceof operator.

 

package instanofexample;

public class Example1 {
	public static void main(String[] args) {
	
		Object obj = "ram";
		String s1 = (String)obj;//downcasting
		System.out.println(s1);
		
	}
}

Output is – ram

Note :- The above code will execute fine. Nothing wrong we have Object obj which containing String, Since we know this object(obj) contains  String value we will downcast to String and we will print that value. Imagine we don’t know what kind of data Object contains. For example, Object is coming from Database. Now we don’t know which kind of data it contains. It may be String or Integer or Float or any entity. If that object contains the string and by mistake, someone downcast into Integer instead of  String. Our code will compile successfully but runtime it will throw ClassCastException.

Let’s see an example where we will try to cast String type object into Integer.

package instanofexample;



public class Example1 {
	public static void main(String[] args) {
		
	    Object obj = "ram";// this is dummy value imagine it may Integer/String/Float
	    Integer s1 = (Integer)obj;
	    System.out.println(s1);
		
	}
}

Output is –

Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at instanofexample.Example1.main(Example1.java:9)


 

Is it not a better option we check What type of data Object obj contains. For now assume Object obj can have Integer, String and Float.

package instanofexample;



public class Example1 {
	public static void main(String[] args) {
		
	    Object obj = "ram"; // dummy value, think it may be String,Integer or Float
	    
	    if(obj instanceof String) {
	    	String s1 = (String)obj;
	    	System.out.println("object containing string  " +s1);
	    }else if(obj instanceof Integer) {
	    	Integer i1 = (Integer)obj;
	    	System.out.println("object containing integer " +i1);
	    }else{
	    	Float f1 = (Float)obj;
	    	System.out.println("object containing float   " +f1);
	    }
		
		
	}
}

Output is – object containing string ram

 

This is the one possible scenario where we can use the instanceof operator.

 

Use of instanceof operator with the interface – Let’s see an example which tells how instanceof operator works in case of the interface.

package instanceofExample;

interface I1 {

}

class Hello implements I1 {

}

public class InstanceOfInterface {
	public static void main(String[] args) {

		// i1 reference of I1 but object of Hello
		I1 i1 = new Hello();
		// instanceof operator will return true for i1
		if (i1 instanceof I1) {
			System.out.println("if condition executed");
		}

		Hello h1 = new Hello();
		// instanceof operator will return true for h1
		if (h1 instanceof I1) {
			System.out.println("if condition executed");
		}
	}
}

Output is –

if condition executed
if condition executed

 

Real time scenario which tells how to use instanceof operator –  Let’s see what is the problem without instanceof operator.


 

package instanofexample;

class Book {
	String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	
}


class Story{
	String storyName;

	public String getStoryName() {
		return storyName;
	}

	public void setStoryName(String storyName) {
		this.storyName = storyName;
	}
	
}


public class Example1 {
	public Object[] getObjectArray() {
		Object [] objArray = new Object[2];
		
		Book book = new Book();
		book.setBookName("alchemist");// setting bookName

		Story story = new Story();
		story.setStoryName("thirsty crow");// setting storyName

	    objArray[0] = book;
		objArray[1] = story;
		
		return objArray;
	}
	
	public static void main(String[] args) {
		
		Example1 ex1 = new Example1();
		Object [] objArrayReturned = ex1.getObjectArray();
		
		for(Object object : objArrayReturned) {
			
			Book b1 = (Book)object;
			System.out.println("book name is "+b1.getBookName());
			
			Story s1 = (Story)object;
			System.out.println("story name is "+s1.getStoryName());
			
		}
		
	   
		
		
	}
}

 

Output is –

book name is alchemist
Exception in thread “main” java.lang.ClassCastException: instanofexample.Book cannot be cast to instanofexample.Story
at instanofexample.Example1.main(Example1.java:57)

 

Solution – we can use instanseof operator.

package instanofexample;

class Book {
	String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	
}


class Story{
	String storyName;

	public String getStoryName() {
		return storyName;
	}

	public void setStoryName(String storyName) {
		this.storyName = storyName;
	}
	
}


public class Example1 {
	public Object[] getObjectArray() {
		Object [] objArray = new Object[2];
		
		Book book = new Book();
		book.setBookName("alchemist");// setting bookName

		Story story = new Story();
		story.setStoryName("thirsty crow");// setting bookName

	    objArray[0] = book;
		objArray[1] = story;
		
		return objArray;
	}
	
	public static void main(String[] args) {
		
		Example1 ex1 = new Example1();
		Object [] objArrayReturned = ex1.getObjectArray();
		
		for(Object object : objArrayReturned) {
			
			if(object instanceof Book) {
				Book b1 = (Book)object;
				System.out.println("book name is "+b1.getBookName());
			}
			
			if(object instanceof Story) {
				Story s1 = (Story)object;
				System.out.println("story name is "+s1.getStoryName());
			}
			
			
		}
		
	   
		
		
	}
}

Output is –

book name is alchemist
story name is thirsty crow


 

instanceof operator with a null reference-

package instanofexample;



public class Example {
public static void main(String[] args) {
	
	Example e = null;
	
	if(e instanceof Example) {
		System.out.println("e is instance of Example");
	}else {
		System.out.println("e is null here");
	}
	
}
}

Output is – e is null here

That’s all about instanceof operator in java.

You may like.

 

instanceof operator java docs.