Site icon DataFlair

Java Null – 7 Unknown Facts about Null in Java

Java Null

Free Java courses with 37 real-time projects - Learn 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.

Important Facts about Null

There are some facts that are essential to know when you are working with null 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 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)

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!

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!

Best Ways to Use Null

The following are recommended practices to bear in mind when utilizing null in Java:

  • Beware of null references: Before using a reference variable, always take into account the possibility that it might be null.
  • Make strategic use of null checks: Only when required, add null checks to avoid NullPointerExceptions.
  • Examine alternatives to null: You may be able to completely avoid null references by redesigning your program in certain situations.
  • Null usage of documents: If you choose to use null, be sure to explain its purpose and methodology in order to make the code easier to read.

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.

Exit mobile version