Java Null – Explore the Unknown Facts about Null in Java

Java and Null share a unique bond with each other. Almost all Java developers face troubles with the NullPointerException, which is the illest-reputed fact about Java Null. Because, the null variables, references, and collections are tricky to handle in Java code. Not only they are hard to identify, but also complex to deal with. Instead of ruing about Java null, it is better to learn more about it and make sure we use it correctly.

In this Java article today, we are going to discuss what is Java Null and its seven unknown facts in Java Programming Language. We will also explore some techniques to minimize null checks and how to avoid nasty null pointer exceptions.

What is Java Null?

In Java, null is a keyword much like the other keywords public, static or final. It is just a value that shows 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. When you declare a boolean variable, it gets its default value as false. Similarly, any reference variable in Java has null as a default value. We use null to denote “no object” or “unknown” or “unavailable”, but these meanings are application-specific.

Some Unknown Facts About Null in Java

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

1. Java Null is Case Sensitive

The “null” in Java is literal and we know that Java keywords are case sensitive. So, we cannot write null as Null or NULL. If we do so, the compiler will not be able to recognize them and give an error. For example,

Object obj = NULL;  // Not Accepted
Object obj = Null;  // Not Accepted
Object obj1 = null  //Accepted

Code to understand that Java null is case-sensitive:

public class Example
{
  public static void main (String[] args) throws java.lang.Exception
  {
    // compile-time error
    Example obj = NULL;

    //runs successfully
    Example obj1 = null;
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
NULL cannot be resolved to a variable at Example.java:6

2. Value of Reference Variable is null

Any reference variable automatically has a null value as its default value.

Code to understand that reference variables have null values:

package com.techvidvan.javanull;
public class NullExamples
{
  private static Object obj;
  private static Integer i;
  private static NullExamples t1;

  public static void main(String args[])
  {
    // it will print null;
    System.out.println("Value of Object obj is: " + obj);
    System.out.println("Value of Integer object i is: " + i);
    System.out.println("Value of NullExamples object t1 is: " + t1);
  }
}

Output:

Value of Object obj is: null
Value of Integer object i is: null
Value of NullExamples object t1 is: null

3. Type of null

The null is just a special value. It is neither an Object nor a type that we can assign to any reference type and typecast it to any type.

// null can be assigned to String
    String string = null;

// you can assign null to Integer also
Integer myInt = null;

// null can also 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. Autoboxing and Unboxing in Java

We can perform auto-boxing and unboxing operations with null values. We can assign null only to the reference types, not to primitive variables like char, int, double, float or boolean. The compiler will throw a NullpointerException if we assign a null value to a primitive data type in Java. The following code shows this concept.

Code to understand Autoboxing and Unboxing with null:

package com.techvidvan.javanull;
public class NullExamples
{
  public static void main (String[] args) throws java.lang.Exception
  {
    //No error, because we are assigning null to reference type of wrapper class.
    Integer myIntObj = null;

    //There will be an error as we are unboxing null to int type
    int intType = myIntObj;
  }
}

Output:

Exception in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.javanull.NullExamples.main(NullExamples.java:10)

5. instanceof Operator 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.

Code to illustrate the use of instanceof operator with null:

public class NullExamples
{
  public static void main (String[] args) throws java.lang.Exception
  {
    Double d1 = null;
    Double d2 = 3.67;

    //prints false
    System.out.println( d1 instanceof Double );

    //prints true
    System.out.println( d2 instanceof Double );
  }
}

Output:

false
true

6. Using null with Static and Non-static Methods in Java

We can call a static method with reference variables with null values. But, if we call a non-static method on a reference variable with a null value, the compiler will throw NullPointerException. Static methods do not throw the exception because these methods are connected to each other using static binding.

Time to revise the full concept of Java Methods with Techvidvan.

Code to use null with static and non-static methods:

package com.techvidvan.javanull;
public class NullExamples
{
  private static void staticMethod()
  {
    System.out.println("We can call the static method by a null reference\n");
  }
  private void nonStaticMethod()
  {
    System.out.print("We cannot call a non-static method by a null reference.");

  }
  public static void main(String args[])
  {
    NullExamples obj = null;
    obj.staticMethod();
    obj.nonStaticMethod();
  }
}

Output:

We can call the static method by a null referenceException in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.javanull.NullExamples.main(NullExamples.java:17)

7. Equals (==) and Not Equals (!=) Operator

We can use these comparison operators (equal to and not equal to) with a null operator. But, we cannot use it with other arithmetic or logical operators like less than (<) or greater than (>). The expression null == null will return true in Java.

Dive a little deep into the concept of Java Operators in detail with Techvidvan. 

Code to illustrate use of == and != operators in Java:

package com.techvidvan.javanull;
public class NullExamples
{
  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);
  }
}

Output:

null == null is true in Java
true
false

NullPointerException in Java

A NullPointerException is an exception in Java. We 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.

Calling the method for a null reference gives a NullPointerException

When we try to call a method that returns null, then we get a NullPointerException. The below code explains this concept:

package com.techvidvan.javanull;
public class NullExamples
{
  public void doSomething()
  {
    String result = doSomethingElse();
    if (result.equalsIgnoreCase("Success"))
      System.out.println("Success");
  }
  private String doSomethingElse()
  {
    return null;
  }
  public static void main(String args[])
  {
    NullExamples t = new NullExamples();
    t.doSomething();
  }
}

Output:

Exception in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.javanull.NullExamples.doSomething(NullExamples.java:7)
at project1/com.techvidvan.javanull.NullExamples.main(NullExamples.java:17)

Accessing a null array gives a NullPointerException

If we access a null array then it gives a NullPointerException.

package com.techvidvan.javanull;
public class NullExamples
{
  private static void findMax(int[ ] arr)
  {
    int max = arr[0];	//this line gives NullPointerException
    //check other elements in loop
  }
  public static void main(String args[])
  {
    findMax(null);
  }
}

Output:

Exception in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.javanull.NullExamples.findMax(NullExamples.java:5)
at project1/com.techvidvan.javanull.NullExamples.main(NullExamples.java:10)

From the above examples, we can understand that accessing any variables, fields, methods, or array of a null object gives a NullPointerException.

Handling NullPointerException in Java

The most common way of handling the NullPointerException is: by using an if-else condition or a try-catch block to check if a reference variable is null, before dereferencing it.

Code to avoid NullPointerException using if-else condition:

package com.techvidvan.javanull;
public class NullExamples
{
  public void doSomething()
  {
    String result = doSomethingElse();
    if (result != null && result.equalsIgnoreCase("Success"))
    {
      // success
      System.out.println("Success");
    }
    else
      // failure
      System.out.println("Failure");
  }
  private String doSomethingElse()
  {
    return null;
  }
  public static void main(String args[])
  {
    NullExamples t = new NullExamples();
    t.doSomething();
  }
}

Output:

Failure

Summary

Here we come to the end of our article. 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. There are many facts about this null in Java that you should know while programming.

In this article, we discussed the ways which can cause an exception at runtime. I hope now you are familiar with the concept of null and NullPointerException in Java.

Thank you for reading our article. Do share our article on Social Media.

Happy Leaning 🙂

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.