Java Null – 7 Unknown Facts about Null in Java

Before we talk about null in Java, let us go back a few steps and recall what variables in Java are.

Well, simply speaking, they can be thought of as tumblers. And the value of those variables is the water inside the tumbler. Makes sense.
Now, how many types of variables were there?

Well, classifying broadly, there were 2 types.

  1. Reference types
  2. Primitive types

Primitive types are the ones that would hold values, and reference types are the ones that can store references.

Null in Java

Since we just read about primitive and reference types in Java, let’s break down a few points.

When primitive values do not have a value explicitly mentioned by the programmer, the default value is stored based on the data type of the variable.

For example, an uninitialized int variable will have 0 as the default value, a boolean variable will have false as the default value and so on…

But what will the reference variables have if they are not explicitly referencing an object in memory? Yes, you guessed it! They would store null!

This is exactly why we need null in Java. It is used for representing references when they are not pointing to any objects in memory. It has a special purpose.

In java, null is literal. It is the same as true or false. It has a special meaning. Many people confuse it with an identifier or a keyword.

Stay updated with latest technology trends
Join DataFlair on Telegram!!

Important Facts about Null

There are some facts that are essential to know when you are working with null in Java.

  • Null is case-sensitive in nature. This means that you cannot expect NULL to be a “literal” in Java. It’s the same as true and false. These have individual meaning.
  • All reference variables have null as their default value.
  • The compiler is unable to unbox null objects. It throws a NullPointerException.
  • Null is not an instance of any class. Hence a null value will return false if used with the instanceOf operator.
  • Static methods are callable with a reference of the null type.
  • You cannot call non-static methods with a reference of the null type.
  • You can use == and != comparisons with null types in Java.

Java Null Pointer Exception

When the program tries to access a part of the memory which is not initialized by default, then the compiler throws a null pointer exception.

Simply speaking, this is possible when you try to access the 100th element of an array of 50 elements.

Java example to evaluate all the facts of null:

package com.dataflair.javanull;


public class Main
{
    
    private static Object a;
    public static void staticmethodtest()
    {
        System.out.println("This is a static method! ");
    }
    public void nonstaticmethodtest()
    {
        System.out.println("This is a non-static method!");
    }
    public static void main(String[] args) {
        Integer i = null;//null is a reserved word

        //Returns error-> Integer j=NULL;//NULL is invalid.
 
        System.out.println("The default value of a is "+a);

        Integer value1=null
;
        //Returns error -> int value=value1; Cannot unbox null type.
 
        System.out.println(value1 instanceof Integer);//returns false.this is because null isnt an instance of any class. 
        Main ob=null;
        ob.staticmethodtest();
        //Returns error-> ob.nonstaticmethodtest(); This is not possible. NullPointerException.
        String a=null;
        String b=null;
        System.out.println(a==b);//returns true;
    }
}

Output:

false
This is a static method!
true
  • We came to know about the Null Pointer Exception in Java. But now we will learn how to avoid it.

We know that we will encounter a null pointer exception when the compiler tries to access some data which is null.

Any data value which is not present in memory or set to null explicitly will return a Null Pointer Exception if accessed.

A primary example of this would be trying to access an index in the array which is out of bounds. Let us see this with an example.

Program to illustrate Java NullPointerException:

package com.dataflair.javanull;

import java.util.*;

public class Main
{
    public static String nullreturnfunc()
    {
        return null;
        
    }
    public static void main (String[] args) {
        String test;
        test=nullreturnfunc();
        System.out.println(test.charAt(3));
        
        
        
    }
}

Output:

Exception in thread “main” java.lang.NullPointerException
at Main.main(Main.java:21)
  • Now we can either use a try-catch method or a simple if-else block to prevent these types of errors. The try-catch method is the more sensible way to do it. But both work.

The same program when modified becomes:

package com.dataflair.javanull;

import java.util.*;

public class Main
{
    public static String nullreturnfunc()
    {
        return null;
        
    }
    public static void main (String[] args) {
        String test;
        test=nullreturnfunc();
        if(test!=null)
        System.out.println(test.charAt(3));
        else
        System.out.println("The value is null!");
        
        
        
    }
}

Output:

The value is null!
  • Now we try to use try-catch to avoid null pointer exceptions.

We can use any kind of message we want in the catch block.

If you are having difficulty understanding what try-catch is, please refer to our exception handling in Java article.

The program becomes:

package com.dataflair.javanull;
import java.util.*;

public class Main
{
    public static String nullreturnfunc()
    {
        return null;
        
    }
    public static void main (String[] args) {
        String test;
        test=nullreturnfunc();
        try 
        {
            System.out.println(test.charAt(3));
        } 
        catch(Exception e) 
        {
            System.out.println("The value is null!");
        }
    }
}

Output:

The value is null!

Summary

We learned a lot about null in Java. It is essential to have a good grasp of null in Java.

Even experienced Java programmers sometimes run into fatal NullPointerExceptions and have no idea how to fix the bug.

Hence a clear understanding of Java Null will come in handy.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.