DEV Community

Mercy
Mercy

Posted on

What is the null literal and how can it be used in Java applications?

How many of you have encountered a NullPointerException? Today, we would like to discuss the null literal and how it can be used in Java. Feel free to share more in the comments.

The null literal in Java represents the absence of a value or a reference that doesn't point to any object. According to my research, the null keyword in java is a literal. It is neither a data type nor an object. Null represents the absence of a value. If you assign a null to an object of string Class, it does not refer to any value in the memory.

The null cannot be assigned to primitive data types. The reserved word null is case sensitive and cannot be written as Null or NULL as the compiler will not recognize them and will certainly give an error.
null is used as a special value to signify: 1. It can also be used to initialise variables

String str = null; // str does not reference any object

  • Uninitialized state
  • Termination condition
  • Non-existing object
  • An unknown value

The null is used to express a particular value within a program. They are constant values that directly appear in a program and can be assigned now to a variable.

2. Checking for Null Values
NullPointer exception is thrown when you try to use a variable with a null value, so to avoid it, you need to check the NullPointerException as I did below

if (str != null) {
    System.out.println(str.length());
} else {
    System.out.println("String is null");
}
Enter fullscreen mode Exit fullscreen mode
  1. Explicitly Dereferencing You can use null to dereference an object and release its memory, then it will be eligible for garbage collection.
MyClass obj = new MyClass();
obj = null; // The object previously referenced by obj is now eligible for garbage collection
Enter fullscreen mode Exit fullscreen mode

Did you know that, you can explicitly add null values in ArrayLists.

List<String> list = new ArrayList<>();
list.add(null); // Adds a null value to the list
Enter fullscreen mode Exit fullscreen mode

Here I mentioned a few of what I have found. Share more in the comments to help others, including me, who want to know more.

Top comments (1)

Collapse
 
ezekiel_77 profile image
Ezekiel • Edited

can we have a short hand boolearn expression

instead of

if (str != null) {
    System.out.println(str.length());
} else {
    System.out.println("String is null");
}
Enter fullscreen mode Exit fullscreen mode

we have

if (str) {
    System.out.println(str.length());
} else {
    System.out.println("String is null");
}
Enter fullscreen mode Exit fullscreen mode