T8Z
T8Z

Reputation: 691

Confuse with String and instance of

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.

Upvotes: 3

Views: 260

Answers (2)

Nambi
Nambi

Reputation: 12042

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();

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 8

Related Questions