Java - null instanceof Object evaluates to both true and false
JavaInstanceofJava Problem Overview
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?
Java Solutions
Solution 1 - Java
This:
" " + obj instanceof Object
is evaluated as:
(" " + obj ) instanceof Object
and " " + obj
is indeed a non-null string which is an instance of Object
.
Solution 2 - Java
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.
Solution 3 - Java
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