Will null instanceof SomeClass
return false
or throw a NullPointerException
?
-
It's also 'important' or at least very useful as a 'best-practise' starting(or very early) line for for any Compare or Equals or similar method that is designed to only succeed on non-null objects of the same type, and guards you against the 'silly cases' in a single line. less code = less bugs. – user1743310 Aug 15 '13 at 9:47
-
14To weigh in on the "is this useful?" debate - I've never written my own Java code (so don't easily know where the specs are, and compiling a test would be very non-trivial), but I'm currently manually converting Java to JavaScript. My code was failing on a null reference, and googling this let me see the accepted answer, which confirmed that it was expected behavior and that I was missing an implicit null check. Very useful, in my case. – Scott Mermelstein Aug 27 '13 at 15:31
No, a null check is not needed before using instanceof.
The expression x instanceof SomeClass
is false
if x
is null
.
From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":
"At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
."
So if the operand is null, the result is false.
-
397This answer is more correct than
try it
because current behavior is not the same as guaranteed behavior. – Luke Jan 8 '13 at 19:08 -
3This question comes into play during Joshua Bloch's chapter on object equality in
Effective Java
- amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 – Kevin Meredith Nov 21 '13 at 13:57 -
17Specifically, in Item 8, he notes that in equals() methods, one instanceof operator serves two purposes - it verifies that the argument is both non-null and of the correct type. "...[S]o you don't need a separate null check." – Andy Thomas Nov 21 '13 at 14:40
-
2@BenThurley - Java's
instanceof
operator was part of Java 1.0, released almost 20 years ago. Changing the behavior now in a way that would break existing code is unlikely, absent some benefit that outweighs that huge cost. Twenty years ago, maybe there could have been arguments for returning true iff the argument could be cast, or throwing an exception for a null argument. But those definitions would have required separate null checks. – Andy Thomas Aug 3 '15 at 13:59 -
3@BenThurley - The behavior is guaranteed by Java specifications past and present. I think Luke's point addresses the limitations of experimentation in determining the guaranteed behavior of the present. – Andy Thomas Aug 3 '15 at 15:43
Using a null reference as the first operand to instanceof
returns false
.
-
278
Very good question indeed. I just tried for myself.
public class IsInstanceOfTest {
public static void main(final String[] args) {
String s;
s = "";
System.out.println((s instanceof String));
System.out.println(String.class.isInstance(s));
s = null;
System.out.println((s instanceof String));
System.out.println(String.class.isInstance(s));
}
}
Prints
true
true
false
false
JLS / 15.20.2. Type Comparison Operator instanceof
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.
API / Class#isInstance(Object)
If this
Class
object represents an interface, this method returnstrue
if the class or any superclass of the specifiedObject
argument implements this interface; it returnsfalse
otherwise. If thisClass
object represents a primitive type, this method returnsfalse
.
-
Kind of confusing. s is a String because it says "String s", s is not a String because it is null. So what the hell is s? – Kai Wang Sep 11 '17 at 15:51
-
1@KaiWang
s
is just an object reference variable. It may refer an actually existing object(""
) or it may refer a(the)null
literal reference. – Jin Kwon Sep 12 '17 at 0:55 -
I'm still confused. s might be null now, but it can only be pointed to a String instance later. It can not be pointed to, like, an Integer. So it is still kind of a String, even it is a null. Just doesn't make much sense... – Kai Wang Sep 12 '17 at 14:04
-
@KaiWang You are confusing the variable type with the type of the actual object. Variables aren't instances; they're effectively just pointers.
null
isn't string data, no matter what variable is pointing to it.s instanceof String
is not the same asfield.getType().equals(String.class)
, for example. – Matthew Read Oct 6 '17 at 2:21 -
1@KaiWang you have to imagine that in the call
s instanceof String
thes
gets replaced with the actual value, so that would become"" instanceof String
andnull instanceof String
. Thinking about it like this may make more sense. – Timo Türschmann Feb 1 '18 at 17:08
Just as a tidbit:
Even (
((A)null)
instanceof A)
will return false
.
(If typecasting null
seems surprising, sometimes you have to do it, for example in situations like this:
public class Test
{
public static void test(A a)
{
System.out.println("a instanceof A: " + (a instanceof A));
}
public static void test(B b) {
// Overloaded version. Would cause reference ambiguity (compile error)
// if Test.test(null) was called without casting.
// So you need to call Test.test((A)null) or Test.test((B)null).
}
}
So Test.test((A)null)
will print a instanceof A: false
.)
P.S.: If you are hiring, please don't use this as a job interview question. :D
No. Java literal null
is not an instance of any class. Therefore it can not be an instanceof any class. instanceof
will return either false
or true
therefore the <referenceVariable> instanceof <SomeClass>
returns false
when referenceVariable
value is null.
-
5That explanation sounds strangely circular... but I know what you mean :-) – Kris Apr 28 '17 at 0:15
-
@Kris ty for the comment I got what you mean :). Edited an answer a bit :). – Developer Marius Žilėnas Apr 28 '17 at 4:13
The instanceof
operator does not need explicit null
checks, as it does not throw a NullPointerException
if the operand is null
.
At run time, the result of the instanceof
operator is true if the value of the relational expression is not null
and the reference could be cast to the reference type without raising a class cast exception.
If the operand is null
, the instanceof
operator returns false
and hence, explicit null checks are not required.
Consider the below example,
public static void main(String[] args) {
        if(lista != null && lista instanceof ArrayList) {                     //Violation
            System.out.println("In if block");
        }
        else {
           System.out.println("In else block");
        }
}
The correct usage of instanceof
is as shown below,
public static void main(String[] args) {
     Â
        if(lista instanceof ArrayList){                     //Correct way
            System.out.println("In if block");
        }
        else {
            System.out.println("In else block");
        }
}