instanceof

The instanceof operator returns true if the specified object is of the specified object type.

Syntax

objectName instanceof objectType

Parameters

Parameter Description
objectName Name of the object to compare to objectType.
objectType Object type.

Description

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

You must specify an object on the right side of the instanceof operator. For example, you can specify a string created with the String constructor, but you cannot specify a string literal.

Examples

See also the examples for throw.

Example 1. The following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Example 2. The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

Example 3. The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.