+1 vote
1 view
in Java by (1.1k points)

Will null instanceof SomeClass return false or throw a NullPointerException?

4 Answers

0 votes
by (13.2k points)

No, a null check is not needed before using instanceof. The expression x instanceof SomeClass is false if x is null

public class myclass {

  public static void main(String[] args) {

    myclass mc = null;

    if(mc instanceof myclass){

      System.out.println("YES");

    } else {

      System.out.println("NO");

    }

  }

}

    Output:

     NO

0 votes
by (41k points)

Nope, a null check is not required before using instanceof.

You can read this here in section 15.20.

It's clearly stated that

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise, the result is false."

means, The expression x instanceof SomeClass will be false if x is null. 

Hence, if the operand is null, the instanceof will return false

0 votes
by (40.3k points)

If you are using a null reference as the first operand to instanceof then it'll return false.

Want to learn Java from scratch! Here's the right video on Java provided by Intelloipaat:

0 votes
by (40.3k points)

If you are using this (((A)null)instanceof A), it will return false.

Want to learn SQL from scratch! Refer to this end to end video on SQL:

But, If typecasting null seems surprising, then do 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.)

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...