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.

有帮助吗?

解决方案

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.

其他提示

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top