Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
Infiniteh Avatar asked Sep 06 '12 09:09

Infiniteh


People also ask

Does null evaluate to false in Java?

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).

Does Java Instanceof check for null?

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.

How does Instanceof work in Java?

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 .

IS null an instance of object?

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.


3 Answers

This:

" " + obj instanceof Object

is evaluated as:

(" " + obj ) instanceof Object

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

like image 193
MByD Avatar answered Oct 16 '22 18:10

MByD


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.

like image 43
Dan D. Avatar answered Oct 16 '22 18:10

Dan D.


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

like image 2
mevada.yogesh Avatar answered Oct 16 '22 16:10

mevada.yogesh