Tracks
/
Java
Java
/
Syllabus
/
Nullability
Nu

Nullability in Java

1 exercise

About Nullability

In Java, the null literal is used to denote the absence of a value.

Primitive data types in Java all have a default value and therefore can never be null. By convention, they start with a lowercase letter e.g int.

Reference types contain the memory address of an object and can have a value of null. They generally start with an uppercase letter, e.g. String.

Attempting to assign a primitive variable a value of null will result in a compile time error as the variable always holds a default value of the type assigned.

// Throws compile time error stating the required type is int, but null was provided
int number = null;

Assigning a reference variable a null value will not result in a compile time error as reference variables are nullable.

//No error will occur as the String variable str is nullable
String str = null;

Whilst accessing a reference variable which has a value of null will compile fine, it will result in a NullPointerException being thrown at runtime.

int[] arr = null;

// Throws NullPointerException at runtime
arr.Length;

A NullPointerException is thrown when trying to access a reference variable which is null but requires an object.

To safely work with nullable values, one should check if they are null before working with them which can be done using equality operators such as == or !=:

int[] arr = null;

if(arr != null) {
    System.out.println(arr.length);
} else {
    //Perform an alternate action when arr is null
}
Edit via GitHub The link opens in a new window or tab

Learn Nullability