Java - null Reference Type

Introduction

You can assign a null value to a variable of any reference type.

A null reference variable is referring to no object.

The following code shows how to assign null value to tom.

Employee tom = null;  // tom is not referring to any object
tom = new Employee(); // Now, tom is referring to a valid Employee object

Compare with null

You can use a null literal with comparison operators to check for equality and inequality.

if (tom == null) {
  // tom is referring to null. Cannot use tom for anything
}

if (tom != null) {
   // not null
}

null and primitive type

null is a literal of null type.

You cannot mix reference types and primitive types.

You cannot assign null to a primitive type variable.

// A compile-time error. 
int num = null;

Cannot compare a primitive type to a reference type

int num = 0;
if (num == null) {// A compile-time error. 
}