concept null reference in category java

appears as: null reference, null references, A null reference
Java SE 11 Programmer I Certification Guide

This is an excerpt from Manning's book Java SE 11 Programmer I Certification Guide.

Exam Tip You can access static variables and methods using a null reference.

Functional Programming in Java: How functional techniques improve your Java programs

This is an excerpt from Manning's book Functional Programming in Java: How functional techniques improve your Java programs.

Here, the null reference is a valid parameter. This is sometimes called a business null. Note that this way of handling the absence of data isn’t specific to objects. The port may also be absent, but it can’t be null because it’s a primitive:

Some languages offer lazy evaluation as a standard feature, whether by default or optionally. With such languages, you don’t need to resort to null references and mutable fields. Unfortunately, Java isn’t one of these languages. In Java, the most frequent approach when a value is to be initialized later is to first assign it the null reference if it’s an object type, or a sentinel value if it’s a primitive. This is risky because there’s no guarantee that the value will indeed be initialized to a significant value when needed. A null reference will probably cause a NullPointerException to be thrown, which at least will be noticed if exception handling has been implemented correctly, but a zero value could be an acceptable business value, leading to a program silently using this acceptable but incorrect value.

Alternatively, you could use a Result<A> to represent the value. This would avoid the use of the null reference, but you’d still have to use mutable fields. Because all this stuff is private, it’s acceptable to use null. But if you prefer, you can use a Result (or an Option) to represent the h and t fields.

9.8. Avoiding null references and mutable fields

In section 9.5.1, I said it was easy to modify your Stream class to memoize the head and tail without resorting to null references and mutable fields. Did you find a solution? In fact, memoization of the tail reference isn’t really necessary because the tail itself is a lazy structure (a Stream), so evaluating the reference won’t take a noticeable amount of time. You’ll only memoize the head.

Avoiding null references is easy: you can use Result.Empty instead of null as long as the value is non-evaluated, and use Result.Success to hold the evaluated value. To avoid using mutable fields, you need to produce a new Stream when the value is evaluated. To do so, you’ll use two constructors: one with the non-evaluated head and one with the evaluated one: