Null In Java: Understanding the Basics

Null In Java: Understanding the Basics

What is null in Java? Is null an instance of anything? What’s the difference between a null reference and a null value? And what exactly is going on under the hood with your memory management when you set a variable to null?  

We’ll set out to answer all these questions and more in this quick guide to the basics of null in Java.

  1. What is “null” in Java?
  2. What exactly does the null statement do?
  3. Other details about null in Java
  4. Null keyword
  5. Null used as default
  6. Null with instance of operator
  7. What about NullPointerException?
  8. Conclusion: No need to fear null in Java

What is “null” in Java?

The role of null in Java is a bit infamous. It is perhaps a rite of passage for all Java developers to run into trouble with the dreaded NullPointerException. We’ll get to that later in this article, but understanding how Null works under the hood can help you know when to use it and how to avoid problems.

In Java, null is a literal, a special constant you can point to whenever you wish to point to the absence of a value. It is neither an object nor a type, which is a common misconception newcomers to the Java language have to grapple with.

What exactly does the null statement do?

Null was created to provide a way to point to the absence of something. When you declare a variable in Java, you must assign the type it expects to store in that variable. You might think of variables as containers that store values of one of the two major categories of types:

  • Primitives are predefined data types provided by the programming language. When you declare a variable as a primitive type (e.g., int, float) your variable directly contains the underlying value.  
  • References are pointers that point to the values being represented. When you declare a variable as a reference type you are storing the address that points to the value rather than the value itself. Classes, arrays, and strings are examples of reference types.

Primitive types cannot have null values, but null can be assigned to any reference type. Here’s an example:

--CODE language-markup line-numbers--
//You can assign null to reference types like strings
String myStr = null;

//Similarly you can assign null to the reference type class that points to a primitive type like "int"
Integer a = null;
//But not directly to the primitive type "int"
int myInt = null;
// Will throw the following error: "incompatible types : required int found null"

Null objects can also be cast to any type at both compile time and runtime.

--CODE language-markup line-numbers--
// Typecasting null to the Integer Class
Integer objInt = (Integer) null;

//Typecasting null to the Double Class
Double objDbl = (Double) null;

Other details about null in Java

While it is generally simple enough to grasp the concept of null in a broader programming sense as a way to point to the absence of a value, in practice we must familiarize ourselves with the nuances of null in any given programming language.

Null keyword

Null is a reserved keyword in the Java programming language. It’s technically an object literal similar to True or False.

Null is case sensitive, like any other keyword in Java.

--CODE language-markup line-numbers--
//This will throw a compile-time error

Integer errInt = NULL;

//Returns compile-time error : can't find symbol 'NULL'

Integer Int = null; 

 //Will assign the integer class Int to a null value

When programming in Java, it’s important to write null in lowercase. Both Null and NULL will throw compile-time errors.

Null used as default

Just as there is a default value for primitive types (e.g., 0 for integers, false for booleans), null is the default value for reference types. Null serves as the default value of any uninitialized reference variable, including instance variables and static variables (although you will still receive a compiler warning for uninitialized local variables). Consider the following Java code sample.

--CODE language-markup line-numbers--
public class Main {
   // Uninitialized variable of reference type will store null until initialized
    private static Object emptyObject;

    // Uninitialized integer is a primitive type so it will store a value (e.g., 0) 
    private static int emptyInt;
    public static void main(String[] args) {
        // Initialized integer with value 20.
        int regInt = 20;

            // Prints 20
            // Prints 0
            // Prints null

Using null with the instanceOf operator

If you want to know whether an object is an instance of a specific class, subclass, or interface you can check it with the instanceOf operator. It’s important to note that the instanceOf operator will return false if used on any reference variable with a null value or the null literal itself.

What is the NullPointerException in Java?

The java.lang.NullPointerException is thrown in Java when you point to an object with a null value. Java programmers usually encounter this infamous pointer exception when they forget to initialize a variable (because null is the default value for uninitialized reference variables).

Common scenarios where a programmer might encounter a NullPointerException include:

  • Calling an uninitialized variable
  • Accessing or modifying a data field or member with a null object
  • Passing a null object as an argument to a method
  • Invoking a method with a null object
  • Synchronizing a null object
  • Throwing a null object
  • Treating a null object as a Java array

So how can you avoid the NullPointerException? Simple. Don’t return null.

Besides the obvious (though not necessarily easy) task of ensuring that all variables are initialized correctly and that all object references point to valid values, you can employ a few techniques to handle a NullPointerException.

Check the arguments of a method

--CODE language-markup line-numbers--
private static void CheckNull(String myStr) {
    if (myStr != null) {
    } else {
        // Perform an alternate action when myStr is null
        System.out.println “Please pass a valid string as an argument”

Use a ternary operator

--CODE language-markup line-numbers--
//boolean expression ? value1 : value2;

String myStr = (str == null) ? "" : str.substring(0, 20);

//If str’s reference is null, myStr will be empty. Else, the first 20 characters will be retrieved.

Return empty collections instead of null

It’s considered best practice to return empty collections instead of null values.

--CODE language-markup line-numbers--
public class emptyString {
     private static List<Integer> numbers = null;

     public static List<Integer> getList() {
          if (numbers == null)
               return Collections.emptyList();
               return numbers;

Conclusion: No need to fear null in Java

In this article, we covered what null is, its properties in Java, and ways you can handle the infamous NullPointerException. As a convenient way to point to the absence of a value, null throws errors when developers forget to initialize their variables before calling them. By checking for null or using programming techniques that avoid returning null values altogether, you won’t just avoid the NullPointerException, but you will also become a better Java programmer.

Ready to apply your Java programming skills to a paid project? Find quality Java programming jobs on Upwork, the world’s work marketplace.  

Projects related to this article:
No items found.

Author Spotlight

Null In Java: Understanding the Basics
Yoshitaka Shiotsu
Technical Copywriter & SEO Consultant

Yoshitaka Shiotsu is a project engineer turned technical copywriter and SEO consultant who regularly contributes to the Upwork Resource Center. He specializes in helping tech companies, startups, and entrepreneurs set themselves up as voices of authority within their target industries.

Latest articles

X Icon