Thursday, 6 September 2018

null and instanceof operator

Most of the people confused by assuming 'We can check the type of a null reference variable using instanceof operator', but this is not correct.

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

Application.java
package com.sample.app;

public class Application {

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

  /* Since data is null, instanceof return false here */
  if (data instanceof String) {
   System.out.println("'data' is instance of string");
  } else {
   System.out.println("'data' is not instance of string ");
  }
 }
}

Output
'data' is not instance of string

You may like

No comments:

Post a Comment