Frage

I am confusing about instanceof. My understanding is instanceof is check for object type. String is object but in the following program it show do not match. Please explain me.

public class MyTest
{
    static String s;
    public static void main(String args[])
    {
        String str = null;

        if(s instanceof String)
        {
            System.out.println("I am true String");
        }
        else 
        {
            System.out.println("I am false String");
        }
        if(str instanceof String)
        {
            System.out.println("I am true String");
        }
        else 
        {
            System.out.println("I am false String");
        }
    }    
}


The output is 

I am false String
I am false String

Thank advance.

War es hilfreich?

Lösung

The instanceof operator does not test the declared type of a variable; it tests the class of the object (if any) that is referenced by the variable. However, both s and str are null in your code and null is never an instance of any class. If you set s and/or str to an actual string, then the output will change accordingly.

Andere Tipps

JavaDoc

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Check with creating new instance of the class

 String str = new String();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top