Interesting Facts About Null In Java [Null Keyword]

Java and Null share an ill-fated bond. Almost every Java developer had troubles with the NullPointerException. In Java, the null variables, references, and collections are tricky to handle. Not only they are hard to identify, but also complex to deal with. In Java, any operation performed on null variables or references throws a NullPointerException.

Null was there from a long time and Java designer knows that null creates more problems than it solves, but still they went with it. Instead of cursing about Java null, let’s learn more about it and make correct use of it.
Many of you are familiar with null but those, who are not, can learn some old and new things about the null. Let’s revisit and learn some interesting facts about the null in Java.

What is Null in Java?

In Java, null is a reserved word much like the other keywords public, static, or final. It is a literal value that tells us that the object is referring to nothing. The invention of the word “null” originated to denote the absence of something. For example, the absence of the user, a resource, or anything. But, over the years it puts Java programmers in trouble due to the nasty Null Pointer Exception.

There are some interesting facts about the null in Java that you should know to become a good programmer in Java.

1) Java null is case sensitive

In Java, null is a reserved word (keyword) for literal values. It seems like a keyword, but actually, it is a literal similar to true and false. The reserved word null is case sensitive and we cannot write null as Null or NULL, the compiler will not recognize them and give an error.

Object object1 = NULL; // Not Ok - This will give Compile time error
Object object2 = Null; // Not Ok - This will give Compile time error
Object object3 = null; // Ok

Programmers which are coming from other languages have this problem, but the use of modern-day IDE’s such as Eclipse, IntelliJ, VSCode, and others has made it insignificant.

2) Null – Default Value for Reference Variable

In Java, there are two major categories of types: primitive and reference. Variables that are declared of type primitive store values whereas variables declared as reference types store references. Every variable type in Java has a default value (e.g. int has 0, boolean has false) if not initialized at the time of declaration. null is the default value of any reference type which is not initialized at the time of declaration. This is true for all kinds of variables, instance variable or static variable, except that compiler will warn you if you use a local variable without initializing them.

public class JavaNull {
    private static String string;
    public static void main(String args []) {
        System.out.println("Value of My string is : "+string);

3) Type of null

Many Java developer has a misconception that null in java is an object. But, the truth is null is neither an Object nor a type that we can assign to any reference type and typecast it to any type. It’s just a special value, which can be assigned to any reference type. You can also typecast null to any type, as below –

// null can be assigned to String
String string = null;
// you can assign null to Integer
Integer myInt = null;
// null can  be assigned to Double
Double myDouble = null;
// null can be type cast to String
String myStr = (String) null;
// We can also type cast it to Integer
Integer myInt1 = (Integer) null;
// yes it's possible, no error
Double myDouble1 = (Double) null;

4) Assigning null to Variables

null is only assigned to a reference variable. You cannot assign null to primitive variables (e.g. int, double, float, or boolean). The compiler will complain if you do so, as below –

// type mismatch : cannot convert from null to int 
int i = null;
// type mismatch : cannot convert from null to short 
 short s = null;
// type mismatch : cannot convert from null to byte 
byte b = null;
//type mismatch : cannot convert from null to double
double d = null;
// this is ok
Integer itr = null;
// this is also ok, but NullPointerExcep

As shown above, when you directly assign null to primitive, it gives a compile-time error. If you assign null to a wrapper class object and then assign that object to the respective primitive type, the compiler doesn’t complain. In this case, it would greet you by null pointer exception at runtime. This happens because of autoboxing in Java.

5) Auto-boxing and Unboxing with null

Any wrapper class with value null will throw java.lang.NullPointerException when Java unbox them into primitive values. Some Java programmer makes mistakes assuming that autoboxing will take care of converting null into default values for respective primitive type e.g. 0 for int, false for boolean, etc, but that’s not true, as shown below –

public class JavaNull {
    public static void main(String[] args) {
        Boolean iAMBooleanObj = null; 
        boolean iAMbooleanType = iAMBooleanObj; // No Compilation Error here but this will throw Runtime Exception of NPE

When you run the above code snippet you will see an Exception in the “main” thread java.lang.NullPointerException  in your console.

6) instanceof Operator and null in Java

The use of the instanceof operator to test whether the object belongs to the specified type of class or subclass or interface. The instanceof operator evaluates to true if the value of the expression is not null. The instanceof operation is very useful for checking the typecasting.

instanceof operator will return false if used against any reference variable with null value or null literal itself.

public class JavaNull {
    public static void main(String[] args) {
        Boolean boolean1 = null;
        Boolean boolean2 = false;
        //prints false
        System.out.println( boolean1 instanceof Boolean );
        //prints true
        System.out.println( boolean2 instanceof Boolean );

7) Calling Static and Non-Static methods on null object

You cannot call a non-static method on a reference variable with a null value, it will throw a NullPointerException. You might not be aware that, you can call the static method with reference variables with null values. Since static members belong to the class rather than an instance, there is no need for an instance while invoking a static member or method.

public class JavaNull {
    public static void main(String[] args) {
        JavaNull object = null;
    private static void staticMethod(){
        System.out.println("We can call the static method by a null reference.");
    private void nonStaticMethod(){
        System.out.print("We cannot call a non-static method by a null reference.");

8) Comparing nulls in Java

You can compare null value using ==  (equal to ) operator and !=  (not equal to) operator, but cannot use it with other arithmetic or logical operator e.g. < (less than) or > (greater than). In Java null == null will return true, as below –

public class JavaNull {
    public static void main(String[] args) {
        String string1 = null;
        String string2 = null;
        if(string1 == string2){
            System.out.println("null == null is true in Java");
        System.out.println(null == null);
        System.out.println(null != null);
null == null is true in Java

9) Passing null as method argument

You can pass null to methods, which accepts any reference type like public void print(Object obj) can be called as print(null). This is OK from the compiler’s point of view, but the behavior entirely depends upon the method. Null safe method doesn’t throw NullPointerException in such a case, they just exit gracefully. It is recommended to write a null safe method if business logic allows.

10) NullPointerException in Java

A NullPointerException is a runtime exception in Java. You get a NullPointerException when an application tries to use an object reference with a null value. If we try to access a null reference then there is a NullPointerException or when we attempt to use null in a case where there is a requirement of an object.

That’s all facts about Null In Java. Null in Java is the reason for many troubles to the developers while they’re programming. It should be handled properly so as to avoid the NullPointerException.