Java - null instanceof Object evaluates to both true and false

JavaInstanceof

Java 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInfinitehView Question on Stackoverflow
Solution 1 - JavaMByDView Answer on Stackoverflow
Solution 2 - JavaDan D.View Answer on Stackoverflow
Solution 3 - Javamevada.yogeshView Answer on Stackoverflow