Conceptcore
Null reference
Also called null pointer, nil, None, nullable type, null safety.
A null reference is a reference value that refers to no object. It marks a missing value. In many languages every reference type includes it, so the type does not show if a value can be absent.
- Applies to
- core-languages
Idea
A reference names an object in memory. A program often needs a reference that names no object. Examples are the end of a linked list, a key that is not in a map, and a field that has no value yet. A null reference fills this role. It is one special value of a reference type, and it refers to no object.
C. A. R. Hoare proposed this value in 1965, in a paper on records for an extension of ALGOL 60. He added null so that a reference field could represent a relationship that has no value for some records. His paper then says: "This value fails to refer to a record, and any attempt to use it to refer to a record leads to an undefined result."1
The second half of that sentence is the problem. In Java, the null reference can be assigned to every reference type.2 A variable of type String holds a string or null, and the type does not tell which. The compiler accepts name.length() in both cases. The error comes at run time, at the place where the program uses the value, and not at the place where the null came from.
This code raises NullPointerException, on purpose.
import java.util.Map;
public class Main {
static final Map<String, String> EMAILS = Map.of("ada", "ada@example.org");
static String email(String name) {
return EMAILS.get(name);
}
public static void main(String[] args) {
System.out.println(email("ada").length());
System.out.println(email("bob").length());
}
}
The program prints 15 and then stops with java.lang.NullPointerException: Cannot invoke "String.length()" because the return value of "Main.email(String)" is null. The method email returned null for a missing key, and its return type String did not show that it could.
The Kotlin documentation calls null references "The Billion-Dollar Mistake".3 Languages use two families of fixes. An option type puts the absence into the type, as Option<String> or Maybe String. The program must handle the empty case before it can use the value. Null safety keeps null but splits each reference type in two, such as String and String?. The compiler rejects a member access on the nullable form. Both fixes move the check from run time to compile time.
How it works
The null value
In C, an integer constant expression with the value 0, or such an expression cast to void *, is a null pointer constant. Conversion of a null pointer constant to a pointer type gives a null pointer. A null pointer compares unequal to a pointer to any object or function, and any two null pointers compare equal.4 C++ adds the keyword nullptr, a literal of type std::nullptr_t that is a null pointer constant.5 Its null pointer value is distinct from every pointer to an object or a function.6
Java gives the null reference a type of its own. The null type has no name, and the null reference is its only value. The null reference can be assigned or cast to any reference type.2 Go uses the predeclared nil as the zero value of pointers, functions, interfaces, slices, channels and maps.7 JavaScript has two values for absence. null is the only value of the Null type, and it represents the intentional absence of any object value. undefined is the only value of the Undefined type.8 Python has the object None, the single value of its type. Python uses it for the absence of a value, and a function that does not return a value explicitly returns None.9
What happens on use
A null reference is safe to store, copy and compare. The danger is an access through it: a field read, a method call or an index.
In C, the unary * operator on an invalid pointer value has undefined behaviour, and a footnote names the null pointer as one such value.10 The language does not check. On the test machine, the program below stopped with a fault. AddressSanitizer reported it as a SEGV on the address 0x000000000000, and added the hint that the address points to the zero page.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
struct point {
int x;
int y;
};
int main(void) {
struct point *p = NULL;
printf("before\n");
printf("%d\n", p->x);
return 0;
}
C++ forbids the null reference outright. A reference must be initialized to refer to a valid object or function. A note in the standard says that a null reference cannot exist in a well-defined program. The only way to make one is indirection through a null pointer, which is undefined behaviour.11 Pointers in C++ still have the null value, with the same rules as in C.
Managed languages check every access and turn the fault into an error that the program can see. In Go, *x on a nil pointer, and a field access through a nil pointer, cause a run-time panic.12
This code panics, on purpose.
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
var p *Point
fmt.Println("before")
fmt.Println(p.X)
}
The program prints before, and then the runtime stops it with panic: runtime error: invalid memory address or nil pointer dereference. On the test machine, the next line was [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=...]. The runtime caught the memory fault at address 0 and turned it into a panic.
The Java Virtual Machine throws a NullPointerException when the object reference of a getfield instruction is null.13 The Java language throws it when the target of a method invocation is null.14 .NET throws NullReferenceException when there is an attempt to dereference a null object reference.15 In JavaScript, a property access on null or undefined throws a TypeError. The property access calls ToObject on the base value, and ToObject throws for these two values.16 Python raises an AttributeError when a program reads an attribute of None, because None is an ordinary object without the attribute (see Pitfalls).
Absence in the type: option types
An option type is a separate type for "a value or nothing". Standard ML defines datatype 'a option = NONE | SOME of 'a.17 Haskell defines data Maybe a = Nothing | Just a. A value of type Maybe a either contains a value of type a, as Just a, or is empty, as Nothing.18 A function that may find no result returns Maybe a, not a. The caller cannot use the result as an a before it matches the two cases.
Rust has no null references in safe code. A reference or a Box<T> must be non-null, and a null one is undefined behaviour.19 A value that may be absent has the type Option<T>. For some types T, Rust guarantees that Option<T> has the same size, alignment and call ABI as T. These types include references, Box, function pointers, NonNull pointers and the NonZero integer types. The compiler uses the all-zero bit pattern, which these types cannot have, for None. The documentation calls this the null pointer optimization.20 The Rust example shows that Option<&i32> and &i32 have the same size.
Swift writes an optional type with a question mark: the type of an optional Int is Int?. An optional contains a value of the type or no value, and the special value nil sets the valueless state. Assigning nil to a variable that is not optional is a compile-time error. Optional binding in an if, guard or while statement checks for a value and makes it available in one step. Force unwrapping with a postfix ! gives the value, and on nil it triggers a run-time error.21
Some languages that have null also have an option type in the library. Java has java.util.Optional<T>, a container that may or may not hold a non-null value. Its documentation says that it is primarily for method return types. It also says that a variable of type Optional should never itself be null.22 C++ has std::optional<T>. It stores the contained value within the storage of the optional object and may not use dynamic memory for it.23 In Python, Optional[X] is the same as X | None. It is a hint for a type checker, and the interpreter does not check it.24
Absence in the type: null safety
Null safety keeps null in the language but gives each reference type two forms. The compiler then tracks which form each expression has.
In Kotlin, a variable of type String cannot hold null, and a variable of type String? can. The compiler reports an error when the code accesses length directly on a String?. After a test such as if (b != null), the compiler smart casts b to String. The safe call operator ?. returns null when the receiver is null, and the Elvis operator ?: gives an alternative value. The not-null assertion !! converts a value to a non-nullable type and throws a NullPointerException if the value is null. The documentation lists the remaining causes of a NullPointerException. They are an explicit throw, the !! operator, data that is not consistent during initialization, and Java code.3
C# has nullable reference types. In a nullable context, string? is a reference that may be null, and string is a reference that should not be null. The compiler runs a null-state analysis and gives warnings. The feature is entirely a compile-time feature, and the run-time behaviour of the program does not change.25 A typical warning is CS8602, "Dereference of a possibly null reference".26
TypeScript has the compiler option strictNullChecks. When it is off, the language ignores null and undefined, which can then appear in place of any type. When it is on, null and undefined have their own types. The checker then reports an error where the code uses them in place of a concrete value.27 The checker narrows a union such as string | null after a test. The postfix ! operator removes null and undefined from a type without any check at run time.28
Null-aware operators
Several languages have operators that test for null as part of an expression. In JavaScript, an optional chain a?.b evaluates to undefined when a is null or undefined.29 The coalescing operator a ?? b returns a unless it is undefined or null.30 C# has ?. and ?[], which return null for a null operand.31 It also has ??, which returns its left operand when that operand is not null, and ??=.32 Kotlin has ?. and ?:.3 These operators make a check shorter, but they do not make it required. A plain . on a nullable value still compiles in JavaScript and in C#.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Native | |
| SQL | Does not apply | SQL NULL is a marker for a missing value in a column, with three-valued logic in comparisons. A query has no references to dereference. |
| Bash | Does not apply | Bash variables hold strings and arrays of strings, not references to objects. |
| PowerShell | Native | |
| HTML | Does not apply | Markup has no references that a program dereferences. |
| CSS | Does not apply | Style rules have no references that a program dereferences. |
| Regular expressions | Does not apply | A pattern has no values or references. |
The example files show how each language marks a value that may be absent. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | native | None; Optional[X] is a hint for a type checker |
| JavaScript | native | null and undefined; ?. and ?? |
| TypeScript | native | null and undefined as types of their own under strictNullChecks |
| Java | native | null in every reference type; Optional<T> in the library |
| C | native | the null pointer, written NULL or 0 |
| C++ | native | nullptr for pointers; references cannot be null; std::optional<T> |
| C# | native | null; nullable annotations with warnings; Nullable<T> for value types |
| Go | native | nil for pointers, functions, interfaces, slices, channels and maps |
| Rust | stdlib | no null references in safe code; Option<T> |
| Kotlin | native | T? separate from T, checked by the compiler |
| PowerShell | native | the automatic variable $null33 |
| Bash | n/a | variables hold strings, not references |
| SQL | n/a | NULL marks a missing value in a column; it is not a reference |
| Regex | n/a | a pattern has no references |
| HTML/CSS | n/a | markup and style rules have no references |
SQL also uses the word NULL, for a different idea. A NULL in a column marks a missing value, and a comparison with it gives an unknown result. A query does not dereference anything, so the concept of this page does not apply.
def find_user(users: list[dict], name: str) -> dict | None:
for user in users:
if user["name"] == name:
return user
return None
def log(message: str) -> None:
print(message)
users = [{"name": "ada", "age": 36}]
for name in ["ada", "bob"]:
user = find_user(users, name)
if user is None:
print(name, "not found")
else:
print(name, user["age"])
result = log("no return statement")
print(result, type(result).__name__, bool(result))
print(bool(0), bool(""), bool([]))
ada 36
bob not found
no return statement
None NoneType False
False False False
- Verdict: native.
Noneis the single value of the typeNoneType, and it marks the absence of a value. - Any name, element or attribute can hold
None, whatever its annotation says. The interpreter does not check annotations.dict | NoneandOptional[dict]are hints for an external type checker. - A function that ends without a
returnstatement returnsNone, aslogshows. A barereturnalso returnsNone. - Test for absence with
is None.Noneis false in a Boolean context, but so are0,""and[]. A testif not userdoes not separate a missing value from an empty one.
#include <map>
#include <optional>
#include <print>
#include <string>
std::optional<int> age(const std::map<std::string, int>& ages, const std::string& name) {
auto it = ages.find(name);
if (it == ages.end()) {
return std::nullopt;
}
return it->second;
}
int main() {
std::map<std::string, int> ages{{"ada", 36}};
for (const char* name : {"ada", "bob"}) {
if (auto a = age(ages, name)) {
std::println("{}: {}", name, *a);
} else {
std::println("{}: unknown", name);
}
}
std::println("{}", age(ages, "bob").value_or(0));
int* p = nullptr;
std::println("{}", p == nullptr);
}
ada: 36
bob: unknown
0
true
- Verdict: native. A pointer can hold the null pointer value, written
nullptr, which compares unequal to a pointer to any object. A C++ reference cannot be null in a well-defined program. - Indirection through a null pointer is undefined behaviour. The language does not check it, but a build with AddressSanitizer reports it at run time (the concept page shows this for C).
std::optional<T>holds aTor nothing, and stores theTinside theoptionalobject with no heap allocation.value()throwsstd::bad_optional_accesswhen it is empty.*and->on an emptyoptionalare undefined behaviour.
import java.util.Map;
import java.util.Optional;
public class Main {
static Optional<String> email(Map<String, String> emails, String name) {
return Optional.ofNullable(emails.get(name));
}
public static void main(String[] args) {
Map<String, String> emails = Map.of("ada", "ada@example.org");
String raw = emails.get("bob");
System.out.println(raw == null);
System.out.println(email(emails, "ada").map(String::length).orElse(0));
System.out.println(email(emails, "bob").orElse("none"));
System.out.println(email(emails, "bob").isPresent());
}
}
true
15
none
false
- Verdict: native. Every reference type includes
null. A variable of typeStringcan holdnull, andMap.getreturnsnullfor a missing key. - Field access, method calls and unboxing on
nullthrowNullPointerException. The message names the expression that wasnull. java.util.Optional<T>is a library class for a result that may be absent.ofNullableconverts a possiblynullvalue, andmap,orElseandorElseThrowwork on the result without anulltest.- The API documentation says that
Optionalis primarily for method return types, and that a variable of typeOptionalshould never itself benull.
#include <stdio.h>
#include <string.h>
struct user {
const char *name;
int age;
};
static const struct user *find(const struct user *users, size_t n, const char *name) {
for (size_t i = 0; i < n; i++) {
if (strcmp(users[i].name, name) == 0) {
return &users[i];
}
}
return NULL;
}
int main(void) {
struct user users[] = {{"ada", 36}, {"alan", 41}};
const char *names[] = {"alan", "bob"};
for (size_t i = 0; i < 2; i++) {
const struct user *u = find(users, 2, names[i]);
if (u != NULL) {
printf("%s: %d\n", u->name, u->age);
} else {
printf("%s: not found\n", names[i]);
}
}
return 0;
}
alan: 41
bob: not found
- Verdict: native. Every pointer type has a null pointer value. The constant
0, or0cast tovoid *, converts to it, and the macroNULLexpands to such a constant. - A null pointer compares unequal to a pointer to any object or function, so
findcan return it to mean "no match". Any two null pointers compare equal. - The unary
*operator, and so->, on a null pointer is undefined behaviour. The language does not check. A run with AddressSanitizer shows the fault (see How it works on the concept page).
#nullable enable
string? Find(string[] names, string prefix)
{
foreach (var name in names)
{
if (name.StartsWith(prefix)) return name;
}
return null;
}
string[] names = ["Ada", "Alan", "Grace"];
string? hit = Find(names, "Gr");
string? miss = Find(names, "Z");
Console.WriteLine(hit?.Length);
Console.WriteLine(miss?.Length is null);
Console.WriteLine(miss ?? "none");
int? count = null;
Console.WriteLine(count.HasValue);
count ??= 3;
Console.WriteLine(count.Value);
5
True
none
False
3
- Verdict: native. Every reference type includes
null. Member access onnullthrowsNullReferenceException. - In a nullable context,
stringmeans "never null" andstring?means "maybe null". The compiler tracks the null state of each variable and warns, for example with CS8602 "Dereference of a possibly null reference". The warnings do not change the program at run time. ?.and?[]returnnullwhen the operand isnull.??gives a default value, and??=assigns only when the variable isnull.- For a value type,
int?isNullable<int>, a struct withHasValueandValue. It is a different mechanism fromstring?, which is an annotation on a reference type.
const user = { name: "Ada", address: null };
console.log(user.address?.city);
console.log(user.address?.city ?? "unknown");
console.log(user.phone);
console.log(user.phone ?? "no phone");
console.log(null == undefined, null === undefined);
console.log(typeof null, typeof undefined);
const count = 0;
console.log(count || 10, count ?? 10);
undefined
unknown
undefined
no phone
true false
object undefined
10 0
- Verdict: native. The language has two values for absence.
nullis the intentional absence of an object value.undefinedis the value of a variable or a property that has no value. - Reading a property of
nullorundefinedthrows aTypeError(see Pitfalls on the concept page). The optional chaining operator?.returnsundefinedinstead when its base isnullorundefined. - The
??operator returns its right operand only when its left operand isnullorundefined. The||operator also replaces0,""andfalse, as the last line shows. null == undefinedistrue, sox == nulltests for both values.typeof nullis"object".
type User = { name: string; email: string | null };
function domain(user: User): string {
if (user.email === null) {
return "none";
}
return user.email.split("@")[1];
}
const users: User[] = [
{ name: "Ada", email: "ada@example.org" },
{ name: "Bob", email: null },
];
for (const u of users) {
console.log(u.name, domain(u));
}
const found = users.find((u) => u.name === "Eve");
console.log(found?.name ?? "not found");
Ada example.org
Bob none
not found
- Verdict: native. Under
strictNullChecks,nullandundefinedhave their own types.stringdoes not include them, so a value that can be absent has a union type such asstring | null. - The type checker narrows the type. After the test
user.email === nullreturns,user.emailhas the typestring. Without the test, the checker reports an error atuser.email.split. Array.prototype.findreturnsUser | undefined, so the result needs?.or a test.- The checks exist only at compile time. The runner strips the types and does not run the checker. With
strictNullChecksoff,nullandundefinedbelong to every type and the checker reports nothing. - The postfix
!operator removesnullandundefinedfrom a type without a check at run time.
package main
import "fmt"
type Node struct {
Value int
Next *Node
}
func (n *Node) Len() int {
if n == nil {
return 0
}
return 1 + n.Next.Len()
}
func main() {
list := &Node{1, &Node{2, nil}}
var empty *Node
fmt.Println(list.Len(), empty.Len())
var m map[string]int
fmt.Println(m["x"], len(m))
var s []int
s = append(s, 7)
fmt.Println(s, len(s))
}
2 0
0 0
[7] 1
- Verdict: native.
nilis the zero value of pointers, functions, interfaces, slices, channels and maps. A variable of one of these types that has no initializer isnil. *pandp.fon anilpointer cause a run-time panic. A method with a pointer receiver can still be called on anilpointer, because the call does not read through the pointer.Lenuses this to treatnilas the empty list.- A
nilmap acts as an empty map for reads, and anilslice works withlenandappend. A write to anilmap panics (see Pitfalls on the concept page). - An interface value is
nilonly when both its dynamic type and its value are unset. Anilpointer stored in an interface is not equal tonil(see Pitfalls).
use std::collections::HashMap;
use std::mem::size_of;
fn main() {
let mut ages = HashMap::new();
ages.insert("ada", 36);
for name in ["ada", "bob"] {
match ages.get(name) {
Some(age) => println!("{name}: {age}"),
None => println!("{name}: unknown"),
}
}
let bob = ages.get("bob").copied().unwrap_or(0);
println!("{bob}");
println!("{} {}", size_of::<&i32>(), size_of::<Option<&i32>>());
}
ada: 36
bob: unknown
0
8 8
- Verdict: stdlib. Safe Rust has no null reference. A reference or a
Boxmust be non-null, and a null reference is undefined behaviour. - A value that can be absent has the type
Option<T>, an enum with the variantsSome(T)andNone.HashMap::getreturnsOption<&V>. Amatchmust handle both variants, so the compiler rejects code that forgetsNone. unwrap_or,mapand the?operator work on anOptionwithout amatch.unwrappanics onNone(see Pitfalls on the concept page).Option<&T>has the same size as&T, as the last line shows. The compiler uses the all-zero bit pattern, which no reference can have, forNone. This is the null pointer optimization.
fun domain(email: String?): String {
if (email == null) return "none"
return email.substringAfter('@')
}
fun main() {
val emails: List<String?> = listOf("ada@example.org", null)
for (e in emails) {
println(domain(e))
}
val name: String? = emails[1]
println(name?.length)
println(name?.length ?: 0)
println(emails.filterNotNull())
}
example.org
none
null
0
[ada@example.org]
- Verdict: native.
Stringcannot holdnull, andString?can. The compiler rejectsnullfor a non-nullable type, and it rejects a member access such asemail.lengthon aString?. - After
email == nullreturns, the compiler smart castsemailtoString, sosubstringAfterneeds no operator. ?.returnsnullwhen the receiver isnull. The Elvis operator?:gives a default value.!!converts a value to a non-nullable type and throwsNullPointerExceptionwhen it isnull(see Pitfalls on the concept page).filterNotNullturns aList<String?>into aList<String>.- Java types are platform types, so a value from Java can still be
nullat run time.
$value = $null
Write-Output "[$value]"
Write-Output ($null -eq $value)
$ages = @{ ada = 36 }
$age = $ages['bob']
Write-Output ($null -eq $age)
Write-Output ($age ?? 0)
$items = 'one', $null, 'three'
Write-Output $items.Count
$array = @($null)
Write-Output ([bool]($array -eq $null))
Write-Output ([bool]($array -ne $null))
Write-Output ($null -eq $array)
[]
True
True
0
3
False
False
False
- Verdict: native.
$nullis an automatic variable that holds a null value. A missing key in a hashtable, or a variable that was never assigned, gives$null. - In a string,
$nullbecomes an empty string, so"[$value]"prints[]. In a collection,$nullcounts as an element, so$items.Countis 3. - Calling a method on
$nullraises the error "You cannot call a method on a null-valued expression". - Put
$nullon the left of-eqand-ne. With an array on the left,-eqand-nefilter the array and do not test it. For@($null)both filters give a result that is false, as the output shows.$null -eq $arraytests the array itself. - The
??operator gives a default value when the left operand is$null.
Variations and related ideas
- Two kinds of absence. JavaScript has both
nullandundefined. A property that does not exist reads asundefined, andnull == undefinedistrue.34 A testx == nulltherefore matches both values. - Nullable value types. In C#,
int?isNullable<int>, a value type that can be assignednull.35 It is a struct withHasValueandValue, and not an annotation likestring?. - A missing return value. In Python, a
returnstatement without an expression returnsNone, and so does the end of a function body.36 A function can thus returnNoneon one path by accident (see Pitfalls). - Methods on nil. In Go, a method with a pointer receiver can run with a
nilreceiver. Anilmap reads as an empty map, and anilslice works withlenandappend.37 The Go example uses anilpointer as the empty list. - Null in collections. In PowerShell,
$nullcounts as an element of a collection, and it becomes an empty string inside a string.3338 - Related concepts. A null reference is a value of a reference or pointer type (Pointers and references). An access through it raises an error in managed languages (Exception). Option types are generic types (Generics). Null safety is a static check (Static and dynamic typing).
Pitfalls
Unboxing a null wrapper
Java converts between int and Integer without a visible cast. If the Integer is null, the unboxing conversion throws a NullPointerException.39 The line that fails can look like arithmetic.
This code raises NullPointerException, on purpose.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 3);
int apples = stock.get("apple");
int pears = stock.get("pear");
System.out.println(apples + pears);
}
}
The message is java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null. The JVM computes such a message to describe precisely which variable was null.40 The fix is stock.getOrDefault("pear", 0), or a variable of type Integer with a test.
A nil pointer in an interface is not nil
In Go, an interface value holds a type and a value. It is nil only when both are unset. A nil pointer stored in an interface has a type, so the interface is not nil.41 A function that returns a nil *MyError as an error therefore returns an error.
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type MyError struct{}
func (e *MyError) Error() string { return "my error" }
func check(fail bool) error {
var p *MyError
if fail {
p = &MyError{}
}
return p
}
func main() {
err := check(false)
fmt.Println(err == nil)
}
false
The program prints false, although check had no error to report. The fix is to return the literal nil on the success path, and a value of type error only when there is an error.
A write to a nil map
A nil map reads as an empty map, but no elements may be added to it. An assignment to an element of a nil map causes a run-time panic.3742
This code panics, on purpose.
package main
import "fmt"
func main() {
var counts map[string]int
fmt.Println(counts["a"])
counts["a"]++
fmt.Println(counts)
}
The panic message is panic: assignment to entry in nil map. The fix is to create the map with make(map[string]int) or a literal before the first write.
typeof null is "object"
In JavaScript, typeof null evaluates to "object".43 A test with typeof for an object therefore also accepts null, and the next property access fails.
This code runs but gives a wrong answer on purpose.
function describe(value) {
if (typeof value === "object") {
return "object with " + Object.keys(value ?? {}).length + " keys";
}
return typeof value;
}
console.log(describe({ a: 1 }));
console.log(describe(null));
object with 1 keys
object with 0 keys
The second line says that null is an object with 0 keys. The fix is the test value !== null && typeof value === "object". A property access on null throws a TypeError:
This code raises TypeError, on purpose.
const config = { server: null };
console.log(config.server.port);
The message is TypeError: Cannot read properties of null (reading 'port').
Nullable warnings do not stop the program
The C# nullable analysis only gives warnings, and the program keeps the same run-time behaviour.25 A warning that a build ignores becomes a NullReferenceException at run time.
This code raises NullReferenceException, on purpose.
#nullable enable
string? Find(string key) => key == "ada" ? "Ada Lovelace" : null;
string name = Find("bob");
Console.WriteLine(name.Length);
The compiler gives the warning CS8600 for the assignment of a possibly null value to string, and CS8602 for name.Length. The build succeeds. The run then fails with System.NullReferenceException: Object reference not set to an instance of an object. The fix is to keep the type string? and handle the null case. A project can also treat the nullable warnings as errors.
The not-null assertion throws
Kotlin's !! tells the compiler that a value is not null. If the value is null, !! throws a NullPointerException.3 Each !! moves a null check from compile time back to run time.
This code raises NullPointerException, on purpose.
fun main() {
val ages = mapOf("ada" to 36)
val age: Int = ages["bob"]!!
println(age)
}
The run stops with java.lang.NullPointerException, with no message and the line number of the !!. The fix is ages["bob"] ?: 0, or a test with if.
A function that returns None on one path
A Python function returns None when control reaches the end of its body.36 If one branch forgets its return, the caller gets None, and the error appears later, at the first use.
This code raises AttributeError, on purpose.
def title(name):
if name:
return name.title()
names = ["ada lovelace", ""]
for n in names:
print(title(n).upper())
The program prints ADA LOVELACE, and then stops with AttributeError: 'NoneType' object has no attribute 'upper'. A type checker reports this when the function has the return annotation -> str. The fix is an explicit return on every path.
Unwrapping an empty option
An option type helps only when the program handles the empty case. Rust's unwrap returns the value in Some and panics on None. Its documentation discourages it for this reason.44
This code panics, on purpose.
use std::collections::HashMap;
fn main() {
let ages: HashMap<&str, i32> = HashMap::from([("ada", 36)]);
let age = ages.get("bob").unwrap();
println!("{age}");
}
The panic message is called `Option::unwrap()` on a `None` value. In C++, value() on an empty std::optional throws std::bad_optional_access. The operators * and -> have the precondition that the optional contains a value, so on an empty optional they are undefined behaviour.45 Java Optional.orElseThrow() throws NoSuchElementException.46 The fix in each language is a match, a test or a default value.
Cost
- A test. A check against
nullcompares one value. Null-aware operators such as?.and??do the same comparison. - Detection. In C, the language does not check an access through a null pointer.10 Managed runtimes detect it and raise an exception, as the Java and Go programs above show.
- Option types. Rust stores
Option<&T>andOption<Box<T>>in the same size as the reference, so the option costs no memory.20 C++std::optional<T>stores the value in place, without dynamic memory.23 JavaOptionalis a class, so anOptionalresult is a reference to an object.22 - Nullable value types. C#
Nullable<T>is a struct, so anint?needs no heap object.35 - Null safety by annotation. C# nullable reference types exist only at compile time.25 TypeScript types also do not exist at run time, so
strictNullChecksadds no cost to the program.
History
- 1965. C. A. R. Hoare proposed records and references for an extension of ALGOL 60 in "Record Handling", ALGOL Bulletin 21, November 1965. The proposal added the reference value
nullfor relationships that do not always yield a value.147 - 2014. JDK 8, the reference implementation of Java SE 8, reached General Availability on 18 March 2014.48
java.util.Optionaldates from Java 1.8.22 - 2015. Rust 1.0 was released on 15 May 2015.49
Option::unwraphas been stable since Rust 1.0.0.44 - 2016. TypeScript 2.0, released on 22 September 2016, added the
strictNullChecksmode and the typesnullandundefined.5051 - 2019. C# 8.0, released in September 2019, added nullable reference types.52
- 2020. JDK 14 reached General Availability on 17 March 2020. It included JEP 358, Helpful NullPointerExceptions.5340
References
- C. A. R. Hoare, Record Handling, ALGOL Bulletin 21, AB21.3.6, pages 39 to 69 (scanned pages at the Computer History Museum), AB21 p.43, 2.6 Other operations defined for references (the reference value null)
- The Java Language Specification, Java SE 25 Edition, chapter 4, 4.1 The Kinds of Types and Values (the null type and the null reference)
- Kotlin documentation, Null safety, the introduction, and the sections Nullable types and non-nullable types, Check for null with the if conditional, Safe call operator, Elvis operator and Not-null assertion operator
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.3.2.3 Pointers, paragraphs 3 and 4
- Working Draft, Standard for Programming Language C++, N4950, [lex.nullptr] paragraph 1
- Working Draft, Standard for Programming Language C++, N4950, [conv.ptr] paragraph 1
- The Go Programming Language Specification, The zero value
- ECMAScript 2026 Language Specification (ECMA-262), 6.1.1 The Undefined Type, 6.1.2 The Null Type and 4.4.15 null value
- The Python Language Reference, 3.14, Data model, 3.2.1 None
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.5.3.2 Address and indirection operators, paragraph 4 and footnote 102
- Working Draft, Standard for Programming Language C++, N4950, [dcl.ref] paragraph 5 and note 2
- The Go Programming Language Specification, Address operators, and Selectors (a nil pointer and a struct field)
- The Java Virtual Machine Specification, Java SE 25 Edition, chapter 6, 6.5 getfield, Run-time Exception
- The Java Language Specification, Java SE 25 Edition, chapter 15, 15.12.4.4 Locate Method to Invoke
- .NET API reference, NullReferenceException Class, the class summary
- ECMAScript 2026 Language Specification (ECMA-262), 7.1.18 ToObject, and 6.2.5.5 GetValue
- The Standard ML Basis Library, The Option structure, Interface (datatype 'a option = NONE | SOME of 'a)
- Haskell 2010 Language Report, chapter 21 Data.Maybe, 21.1 The Maybe type and operations
- The Rust Reference, Behavior considered undefined, undefined.validity.reference-box
- The Rust Standard Library, Module std::option, Representation
- The Swift Programming Language, The Basics, Optionals, nil, Optional Binding and Force Unwrapping
- Java SE 25 API, Class Optional<T>, the class description, the API Note and Since: 1.8
- Working Draft, Standard for Programming Language C++, N4950, [optional.optional.general] paragraph 1
- The Python Standard Library, 3.14, typing, typing.Optional
- C# documentation, Nullable reference types, the introduction, Nullable context and Null-state analysis
- C# language reference, Resolve nullable warnings, the list of warnings (CS8600, CS8602)
- TypeScript, TSConfig Reference, strictNullChecks
- TypeScript Handbook, Everyday Types, null and undefined, and Non-null Assertion Operator (Postfix !)
- ECMAScript 2026 Language Specification (ECMA-262), 13.3.9.1 Runtime Semantics: Evaluation (OptionalExpression)
- ECMAScript 2026 Language Specification (ECMA-262), 13.13.1 Runtime Semantics: Evaluation (CoalesceExpression)
- C# language reference, Member access operators, Null-conditional operators ?. and ?[]
- C# language reference, ?? and ??= operators, the introduction
- PowerShell, about_Automatic_Variables, $null
- ECMAScript 2026 Language Specification (ECMA-262), 7.2.13 IsLooselyEqual, steps for null and undefined
- .NET API reference, Nullable<T> Struct, the struct summary and declaration
- The Python Language Reference, 3.14, Simple statements, 7.6 The return statement
- The Go Programming Language Specification, Map types (a nil map is equivalent to an empty map except that no elements may be added)
- PowerShell, Everything you wanted to know about $null, Impact of $null, Method on a null-valued expression, and Checking for $null
- The Java Language Specification, Java SE 25 Edition, chapter 5, 5.1.8 Unboxing Conversion
- JEP 358: Helpful NullPointerExceptions, Summary, Non-Goals and the Release field (14)
- Frequently Asked Questions (FAQ), The Go Programming Language, Why is my nil error value not equal to nil?
- The Go Programming Language Specification, Index expressions (for a of map type: a nil map, and assignment to an element of a nil map)
- ECMAScript 2026 Language Specification (ECMA-262), 13.5.3.1 Runtime Semantics: Evaluation (the typeof operator, the case of null)
- The Rust Standard Library, Enum Option, Option::unwrap (the Panics section and the stability mark 1.0.0)
- Working Draft, Standard for Programming Language C++, N4950, [optional.observe] paragraphs 1, 4 and 13
- Java SE 25 API, Class Optional<T>, orElseThrow()
- Computer History Museum, Software Preservation Group, ALGOL standards, the entry C.A.R. Hoare, Record Handling (ALGOL Bulletin Number 21, November 1965, pages 39-69)
- OpenJDK, JDK 8, the project description (General Availability on 18 March 2014)
- Announcing Rust 1.0, The Rust Blog, the post header (May 15, 2015)
- TypeScript 2.0 is now available!, TypeScript blog, the post header (September 22nd, 2016) and the section on null- and undefined-aware types
- TypeScript 2.0 release notes, Null- and undefined-aware types, --strictNullChecks
- The history of C#, C# version 8.0 (Released September 2019, Nullable reference types)
- OpenJDK, JDK 14, the project description (General Availability on 17 March 2020) and the Features list (358)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 77H0VR Edit this page History Report an error Markdown