instanceof Operator in Java

instanceof operator is used to test whether an object is an instance of class.

Example 1 : Greeting Cards

instanceof Operator

instanceof Operator

instanceof operator returns true if c is an instance of BirthdayCard class otherwise false. If the result of instanceof operator is true then corresponding cast expression will always be valid. instance of operator .

Example 2 : Fruit

public class Fruit {
public String toString() {
return "Fruit";
}
}

class Orange extends Fruit {
public String toString() {
return "Orange";
}

}

class Apple extends Fruit {
public String toString() {
return "Apple";
}

}

public class FruitBasket {

public static void main(String[] args) {
Fruit[] fruit = new Fruit[5];

fruit[0] = new Apple();
fruit[1] = new Orange();
fruit[2] = new Apple();
fruit[3] = new Orange();
fruit[4] = new Orange();

int numberOfApples = 0;
int numberOfOranges = 0;
for(int i= 0; i<fruit.length; i++){
if(fruit[i] instanceof Apple )
numberOfApples++;
else if(fruit[i] instanceof Orange)
numberOfOranges++;
}

System.out.println("Total Number of Apples in the basket : "+ numberOfApples);
System.out.println("Total Number of Oranges in the basket : "+ numberOfOranges);
}
}

No Responses

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.