Skip to main content

Java Exception Handling MCQ Test

  Loading…

instanceof operator

In Java, the `instanceof` operator is used to check whether an object is an instance of a particular class or implements a particular interface. It returns `true` if the object is an instance of the specified class or implements the specified interface; otherwise, it returns `false`.

Syntax:

object instanceof ClassName

or

object instanceof InterfaceName


- `object`: The object whose type is to be checked.

- `ClassName`: The name of the class.

- `InterfaceName`: The name of the interface.


Example:


class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

public class Main {

    public static void main(String[] args) {

        Animal a = new Dog();

        System.out.println(a instanceof Animal); // true

        System.out.println(a instanceof Dog);    // true

        System.out.println(a instanceof Cat);    // false

    }

}


In this example:

- `a instanceof Animal` returns `true` because `a` is an instance of `Animal`.

- `a instanceof Dog` returns `true` because `a` is also an instance of `Dog`.

- `a instanceof Cat` returns `false` because `a` is not an instance of `Cat`.


Usage:

- Useful for checking the type of objects before performing operations or casting.

- Helps in implementing polymorphic behavior and dynamic dispatch.


Note:

- The `instanceof` operator returns `false` if the object is `null`.

- It's often used in conjunction with conditional statements, casting, and polymorphism to write more flexible and robust code.

Comments

Popular posts from this blog

Iterators and Collections

In Java, iterators are objects that allow for sequential access to the elements of a collection. The Java Collections Framework provides the Iterator interface, which defines methods for iterating over collections such as lists, sets, and maps. Here's an explanation of iterators and their relationship with collections, along with examples: Iterator Interface: The Iterator interface provides methods to iterate over the elements of a collection sequentially: - boolean hasNext(): Returns true if there are more elements to iterate over. - E next(): Returns the next element in the iteration. - void remove():  Removes the last element returned by `next()` from the underlying collection (optional operation). Collections and Iterators: 1. Collection Interface:    - Collections represent groups of objects, such as lists, sets, and maps.    - They provide methods for adding, removing, and accessing elements. 2. Iterator Usage:    - Collections implement the Iter...

The Collection Interface.

  The Collection Interface.