Friday, 24 January 2020

Is null instance of anything?


No, null is not instance of anything. If you compare null with instanceof operator, it always return false.

As per Java specification, 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.

App.java
package com.sample.app;

public class App {

 public static void main(String[] args) {
  String str = null;

  Integer i1 = null;

  if (str instanceof String) {
   System.out.println("str is instance of String");
  } else {
   System.out.println("str is not instance of String");
  }

  if (i1 instanceof Integer) {
   System.out.println("i1 is instance of Integer");
  } else {
   System.out.println("i1 is not instance of Integer");
  }

 }

}

Output
str is not instance of String
i1 is not instance of Integer

Reference



You may like

No comments:

Post a Comment