Java - null instanceof Object evaluates to both true and false

When I compile and run this code:

public class Testing {
    public static void main(String... args) {
        Object obj = null;
        if (obj instanceof Object) {
            System.out.println("returned true"); 
        } else {
            System.out.println("returned false"); 
        }
        System.out.println(" " + obj instanceof Object);
    }
}

I get this on the command line:

C:\Users\xxxxxx\Desktop>java Testing
returned false
true

Shouldn't "null instanceof someType" always return false?


This:

" " + obj instanceof Object

is evaluated as:

(" " + obj ) instanceof Object

and " " + obj is indeed a non-null string which is an instance of Object.


In the last System.out.println, the " " + obj evaluates first and the result, which is a String is checked for the instanceof Object and the result is printed.


In (" " + obj) is the part which gets evaluated first so its no more null after parenthesis. So it is the instance of Object.

Also refer the below link so your concept will be clear.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html