Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Examples – instanceof Keyword Usage

Java Examples - instanceof Keyword Usage

Java Examples Java Examples

instanceof is a binary operator in Java, similar to ==, >,< and other operators.

instanceof is a reserved keyword in Java. Its role is to test whether the object on its left is an instance of the class on its right, and it returns a boolean data type.

The following example creates the displayObjectClass() method to demonstrate the usage of the Java instanceof keyword:

Main.java file code:

/*

author by runoob.com Main.java

*/

import

java

.

util

.

ArrayList

;

import

java

.

util

.

Vector

;

public

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

Object

testObject

=

new

ArrayList

(

)

;

displayObjectClass

(

testObject

)

;

}

public

static

void

displayObjectClass

(

Object

o

)

{

if

(

o

instanceof

Vector

)

System

.

out

.

println

(

"

The object is an instance of the java.util.Vector class

"

)

;

else

if

(

o

instanceof

ArrayList

)

System

.

out

.

println

(

"

The object is an instance of the java.util.ArrayList class

"

)

;

else

System

.

out

.

println

(

"

The object is an instance of the

"

o

.

getClass

(

)

"

class

"

)

;

}

}

The output of the above code is:


对象是 java.util.ArrayList 类的实例

Java Examples Java Examples