Fundamentals 12 min read

Understanding Null in Java: Causes, Behaviors, and Best Practices

This article explains the role of the null keyword in Java, its default value for reference types, common pitfalls such as NullPointerException caused by autoboxing, improper primitive assignments, instanceof checks, static method calls on null references, and safe handling techniques to write null‑safe code.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Understanding Null in Java: Causes, Behaviors, and Best Practices

For Java programmers, null is a notorious source of NullPointerException (NPE), and even the language's creator admits it was a major mistake; yet null remains part of Java.

Null is a case‑sensitive keyword like public or static ; writing NULL or Null results in a compilation error.

It is the default value for every reference type (objects, wrappers, arrays, etc.), while primitive types have their own defaults (e.g., int defaults to 0, boolean to false).

Example of the default null value for a static field:

private static Object myObj;
public static void main(String args[]){
    System.out.println("What is value of myObj : " + myObj);
}
// Output: What is value of myObj : null

Null can be assigned to any reference type and even cast to any reference type without causing a compile‑time error:

String str = null; // null can be assigned to String
Integer itr = null; // null can be assigned to Integer
Double dbl = null; // null can be assigned to Double
String myStr = (String) null; // cast is allowed
Integer myItr = (Integer) null; // cast is allowed
Double myDbl = (Double) null; // cast is allowed

Assigning null directly to a primitive type is illegal and triggers a compilation error:

int i = null; // compile‑time error
short s = null; // compile‑time error
byte b = null; // compile‑time error
double d = null; // compile‑time error

When null is stored in a wrapper object and later unboxed, a NullPointerException is thrown. Example with autoboxing:

Integer iAmNull = null;
int i = iAmNull; // compiles, but throws NPE at runtime

Using a HashMap without checking for null values also leads to NPE during autounboxing:

import java.util.HashMap;
import java.util.Map;
public class Test {
    public static void main(String args[]) throws InterruptedException {
        Map
numberAndCount = new HashMap<>();
        int[] numbers = {3,5,7,9,11,13,17,19,2,3,5,33,12,5};
        for(int i : numbers){
            int count = numberAndCount.get(i); // returns null
            numberAndCount.put(i, count++); // NPE here
        }
    }
}
// Output: Exception in thread "main" java.lang.NullPointerException

The instanceof operator returns false when its left‑hand operand is null:

Integer iAmNull = null;
if(iAmNull instanceof Integer){
    System.out.println("iAmNull is instance of Integer");
}else{
    System.out.println("iAmNull is NOT an instance of Integer");
}
// Output: iAmNull is NOT an instance of Integer

Static methods can be invoked through a null reference because they are bound at compile time, while invoking a non‑static method on a null reference throws NPE:

public class Testing {
    public static void main(String args[]){
        Testing myObject = null;
        myObject.iAmStaticMethod(); // works
        myObject.iAmNonStaticMethod(); // throws NPE
    }
    private static void iAmStaticMethod(){
        System.out.println("I am static method, can be called by null reference");
    }
    private void iAmNonStaticMethod(){
        System.out.println("I am NON static method, don't call me by null");
    }
}
// Output:
// I am static method, can be called by null reference
// Exception in thread "main" java.lang.NullPointerException

Null can be passed as an argument to any method that accepts an object reference; whether it causes an exception depends on the method’s implementation.

Equality comparisons with null must use == or != ; other relational operators are illegal. In Java, null == null evaluates to true :

String abc = null;
String cde = null;
if(abc == cde){
    System.out.println("null == null is true in Java");
}
if(null != null){
    System.out.println("null != null is false in Java");
}
// Output: null == null is true in Java

In summary, null is the default value for all reference types in Java, cannot be assigned to primitives, and improper handling—especially with autoboxing, collections, or method calls—leads to NullPointerException; understanding these behaviors and applying null‑safe practices makes code more robust.

Javabest practicesautoboxingnullpointerexceptionstatic methodNULLinstanceof
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.