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.
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 : nullNull 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 allowedAssigning 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 errorWhen 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 runtimeUsing 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.NullPointerExceptionThe 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 IntegerStatic 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.NullPointerExceptionNull 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 JavaIn 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.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.