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?
You can't compare null to a boolean . They are different types one indicating a null reference pointer and the other a false/not true value. Thus the answer is: No this expression is not even valid (and if it was, it would be false).
Using the instanceof Operator When an Object Is null If we use the instanceof operator on any object that's null, it returns false. We also don't need a null check when using an instanceof operator.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
You can assign a null value to any reference variable. But the null value is not an instanceof Object or any other class. When you assign a reference variable null, it means that the reference variable doesn't refer to any object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With