Languages
[Edit]
EN

Java - instanceof keyword simple usage example

4 points
Created by:
Nikki-Mathews
517

In java with instanceof keyword we can check if our object is instance of specific class or interface.

Quick solution:

List<String> results = new ArrayList<>();

if (results instanceof List) {
    // results is instance of List
}

Example with ArrayList instead of List:

ArrayList<String> results = new ArrayList<>();

if (results instanceof List) {
    // results is instance of List
}

Example with Object instead of List

Object results = new ArrayList<>();

if (results instanceof List) {
    // results is also instance of List
}

Practical examples

Practical example 1:

import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main(String[] args) {

        List<String> results = new ArrayList<>();

        if (results instanceof List) {
            System.out.println("Yes, results is instance of List");
        } else {
            System.out.println("No, results is NOT instance of List");
        }
    }
}

Output:

Yes, results is instance of List

Practical example 2:

import java.util.ArrayList;
import java.util.List;

public class Example {

    public static void main(String[] args) {

        Object results = new ArrayList<>();

        if (results instanceof List) {
            System.out.println("Yes, results is instance of List");
        } else {
            System.out.println("No, results is NOT instance of List");
        }

        if (results instanceof String) {
            System.out.println("Yes, results is instance of String");
        } else {
            System.out.println("No, results is NOT instance of String");
        }
    }
}

Output:

Yes, results is instance of List
No, results is NOT instance of String

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join