EN
Java - instanceof keyword simple usage example
4 points
In java with instanceof
keyword we can check if our object is instance of specific class or interface.
Quick solution:
xxxxxxxxxx
1
List<String> results = new ArrayList<>();
2
3
if (results instanceof List) {
4
// results is instance of List
5
}
Example with ArrayList instead of List:
xxxxxxxxxx
1
ArrayList<String> results = new ArrayList<>();
2
3
if (results instanceof List) {
4
// results is instance of List
5
}
Example with Object instead of List
xxxxxxxxxx
1
Object results = new ArrayList<>();
2
3
if (results instanceof List) {
4
// results is also instance of List
5
}
xxxxxxxxxx
1
import java.util.ArrayList;
2
import java.util.List;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
8
List<String> results = new ArrayList<>();
9
10
if (results instanceof List) {
11
System.out.println("Yes, results is instance of List");
12
} else {
13
System.out.println("No, results is NOT instance of List");
14
}
15
}
16
}
Output:
xxxxxxxxxx
1
Yes, results is instance of List
xxxxxxxxxx
1
import java.util.ArrayList;
2
import java.util.List;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
8
Object results = new ArrayList<>();
9
10
if (results instanceof List) {
11
System.out.println("Yes, results is instance of List");
12
} else {
13
System.out.println("No, results is NOT instance of List");
14
}
15
16
if (results instanceof String) {
17
System.out.println("Yes, results is instance of String");
18
} else {
19
System.out.println("No, results is NOT instance of String");
20
}
21
}
22
}
Output:
xxxxxxxxxx
1
Yes, results is instance of List
2
No, results is NOT instance of String