Core Java

What is null in Java

In this article, we will discuss the null in java. Java and null share a unique bond across the board, whether we are using it as a default or placeholder or being used as a filler for a variable intentionally.

1. What is null and why it is used?

Recall what a variable is and what a value is. A common analogy will be to consider the variable as a container and value as what the container has inside. Each variable must have a type that will define the kind of value contained within the container.
There are two major categories of types in Java: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references.

Main.java

public class Main {
    private static Object obj;// this is an uninitialised variable of reference type. hence it will store null in it.
    private static int numOne; // this is an uninitialised int. it is of primitive type. so it will store 0 until initialised.

    public static void main(String[] args) {
        int num = 10;// this is an initialised integer with value 10.
        System.out.println(num);
        System.out.println(numOne);
        System.out.println(obj);
    }
}

In the code snippet shown above, we have 3 cases, One is the Object obj and int numOne, which are have not been initialized and int num which is initialized to 10. Since the Object is reference type and int is a primitive type, obj has null stored in it and numOne has 0 stored in it. The output of Main.java is shown in fig 1 below.

null in Java - Output of Main.java
Fig. 1. Output of Main.java

2. Properties of null

In this section we will discuss couple of properties associated with null.

2.1 null keyword

In Java, this word is a reserved word for literal values. It seems like a keyword, but actually, it is a literal similar to true and false.

2.2 null used as defaults

This word is used as a default value for the uninitialized variable of reference types like Object or user-defined class. It will not be used as a default variable for any variable of primitive types, like, int and float.

2.3 Casting null objects to Other Types in Java

Typecasting null to any reference type is fine at both compile-time and runtime. It will not throw any error or exception. The same is shown in the code snippet below.

CastingNull.java

public class CastingNull {
    public static void main(String[] args) {
        String myStr = (String) null; // null can be type cast to String
        Integer myItr = (Integer) null; // it can also be type casted to Integer
        Double myDbl = (Double) null; // yes it's possible, no error
        System.out.println("Printing null casted to String");
        System.out.println(myStr);
        System.out.println("Printing null casted to Integer");
        System.out.println(myItr);
        System.out.println("Printing null casted to Double");
        System.out.println(myDbl);
    }
}

The output of the above code snippet is shown in fig 2 below.

null in Java - Output of  CastingNull.java
Fig 2. Output of CastingNull.java

2.4 null with instanceof operator

instanceof operator will return false if used against any reference variable with null value or null literal itself. We can see it in action in code snippet below

NullWithInstanceOf.java

public class NullWithInstanceOf {
    public static void main(String[] args) {
        Integer variableWithNull = null;
        System.out.println("Checking instanceof with Integer type variable with null stored");
        if (variableWithNull instanceof Integer) {
            System.out.println("variableWithNull is instance of Integer");
        } else {
            System.out.println("variableWithNull is NOT an instance of Integer");
        }
    }
}

The output of the above code snippet is shown in fig 3 below.

null in Java - Output of  NullWithInstanceOf.java
Fig 3. Output of NullWithInstanceOf.java

3. NullPointerException

NullPointerException is a RuntimeException . In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference with null value.

3.1 When is NullPointerException thrown

NullPointerException can be thrown in any case where running java program tries to use an object reference with null value in it. This can happen when java tries to call an instance method on the object referred by a null reference.

3.2 NullPointerException with Static variables

In this section, we will cover the case when we try to use static java variables with a null reference. Java will not throw an NullPointerException in this case. This is explained in the code snippet below.

NullPointerExceptionWithStatic.java

public class NullPointerExceptionWithStatic {
    private static Object unInitialisedStaticObject; // this is an uninitialised static object

    public static void main(String[] args) {
        System.out.println();
        System.out.print("What is the value of unInitialisedStaticObject :: ");
        System.out.println(unInitialisedStaticObject); // java will not throw NullPointerException
    }
}

The output of the above code snippet is shown in fig 4 below.

Fig 4. Output of NullPointerExceptionWithStatic.java

3.3 NullPointerException with non Static variables

In this section we will cover the case when we try to use non static java variables with null reference. Java will throw an NullPointerException in this case. This will happen in case of any wrapper class with value null will throw NullPointerException when Java unbox them into primitive values. This is explained in the code snippet below.

NullPointerExceptionWithNonStatic.java

import java.util.HashMap;
import java.util.Map;

public class NullPointerExceptionWithNonStatic {
    public static void main(String[] args) {
        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 = (int) numberAndCount.get(i); // NullPointerException
            numberAndCount.put(i, count++);
        }
    }
}

The output of the above code snippet is shown in fig 5 below.

Fig 5. Output of NullPointerExceptionWithNonStatic.java

4. null in Java – Summary

To summarize we have covered the common scenarios around the null in java. We have cover how to use it and where to use it and how it can be used as the placeholder for reference type variables. We have also discussed a very common exception associated with i.e., NullPointerException.

6. Download the Source Code

Download
You can download the full source code of this example here: What is null in Java

Last updated on Jul. 28th, 2021

Abhinav Nath Gupta

Abhinav holds a Master degree in Computer Science and Engineering from the National Institute of Technology Karnataka. He has finished his graduation from Information Technology Department in the Anand Engineering College, Agra. During his studies he has been involved with a large number of projects ranging from Networking and Cryptography. He works as a software development engineer at a software development firm in bengaluru where he is mainly involved with projects based on Nodejs. He is interested in cryptography, data security, cryptocurrency and cloud computing, and published articles regarding these topics. He can be reached at abhi.aec89@gmail.com.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button