I. Basic Concepts of Null Values
In programming, a variable does not always contain valid business data.
For example:
- The user did not fill in a phone number.
- A database query found no records.
- The function failed during execution and did not return a valid object.
- A configuration option has not been set.
- An object has not yet been initialized.
- The data returned by a network request is missing a field.
These scenarios all involve missing data, but they do not necessarily have the same semantics.
A null value is usually used to indicate that a value does not exist, is missing, or is invalid, but different languages and systems define null values inconsistently.
The following concepts need to be distinguished:
| Concept | Meaning | Typical representation |
|---|---|---|
| Null Value | An abstract state in which no valid data exists | null, None |
| NULL | A null marker in databases and some languages | SQL NULL |
| null | A null reference or null value in languages such as Java and JavaScript | null |
| None | A singleton object representing no value in Python | None |
| nil | A specific null representation in languages such as Go, Swift, and Objective-C | nil |
| Optional | Expresses through the type structure that a value may or may not exist | Optional<T> |
| Undefined | Represents an undefined value in JavaScript | undefined |
These concepts cannot simply be regarded as the same thing.
In particular, note the following:
NULL is a null-value semantic; Optional is a type-modeling mechanism.
Optional is not another simple null-value literal; rather, it explicitly expresses through the type system that a value may not exist.
II. The Difference Between NULL and null
2.1 NULL in Databases
In relational databases, NULL is used to indicate that a field lacks an available value.
For example:
CREATE TABLE users (
id BIGINT PRIMARY KEY,
name VARCHAR(100),
phone VARCHAR(20)
);
INSERT INTO users (id, name, phone)
VALUES (1, 'Alice', NULL);
Here, the phone field is NULL, indicating that the current record has no available phone number.
However, NULL is not equivalent to the following:
- An empty string
'' - The number
0 - The Boolean value
FALSE - The string
'NULL'
They represent different data states.
SELECT
NULL IS NULL,
'' IS NULL,
0 IS NULL;
The results are, respectively:
TRUE
FALSE
FALSE
NULL in databases has a very important characteristic: it affects SQL logical evaluation.
2.2 null in Programming Languages
In Java:
String name = null;
name is a reference variable that currently does not refer to any object.
String name = "Alice";
name = null;
Setting name to null means that the variable no longer refers to the original string object.
However, this does not mean that the object is necessarily destroyed immediately. The actual reclamation of the object is determined by the garbage collection mechanism and also depends on whether other references exist.
In JavaScript:
let user = null;
null is a primitive value used to explicitly indicate that the variable currently has no object value.
typeof null; // "object"
This is a legacy language behavior in JavaScript. Although typeof null returns "object", null itself is not an ordinary object.
2.3 None in Python
Python uses None to represent no value:
user = None
if user is None:
print("用户不存在")
None is a singleton object of type NoneType.
print(type(None))
# <class 'NoneType'>
When checking for null values in Python, the following is usually used:
if user is None:
...
rather than:
if not user:
...
because not user matches not only None, but potentially also:
False00.0""[]{}
These values may be legitimate business data and do not necessarily indicate missingness.
III. The Special Semantics of NULL: Three-Valued Logic
NULL in a database is not just a special data value; it also changes the rules for evaluating logical expressions.
Traditional Boolean logic has only two outcomes:
- TRUE
- FALSE
SQL, however, introduces a third logical state:
- TRUE
- FALSE
- UNKNOWN
When an expression involves NULL and its truth value cannot be determined, the result is usually UNKNOWN.
3.1 Why Is NULL Not Equal to NULL?
In SQL:
SELECT NULL = NULL;
The result is not TRUE, but UNKNOWN.
The reason is that NULL represents something unknown or missing, and two unknown values cannot be judged equal on that basis.
For example:
- The first user's age is unknown.
- The second user's age is also unknown.
This is no basis for proving that the two people are the same age.
Therefore, SQL uses three-valued logic to handle NULL comparisons.
3.2 Rules for Three-Valued Logical Operations
SQL logical operations mainly follow the rules below.
| A | B | A AND B | A OR B |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE | TRUE |
| TRUE | UNKNOWN | UNKNOWN | TRUE |
| FALSE | FALSE | FALSE | FALSE |
| FALSE | UNKNOWN | FALSE | UNKNOWN |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
Rules for the NOT operation:
| A | NOT A |
|---|---|
| TRUE | FALSE |
| FALSE | TRUE |
| UNKNOWN | UNKNOWN |
Two of these are easy to overlook:
FALSE AND UNKNOWN = FALSE
Because as long as one operand in an AND operation is FALSE, the entire expression cannot be TRUE.
TRUE OR UNKNOWN = TRUE
Because as long as one operand in an OR operation is TRUE, the entire expression is already TRUE.
3.3 NULL Checks in SQL Queries
Incorrect approach:
SELECT *
FROM users
WHERE phone = NULL;
This condition will not filter out NULL data as expected.
Because:
phone = NULL
evaluates to UNKNOWN, not TRUE.
Correct approach:
SELECT *
FROM users
WHERE phone IS NULL;
To filter non-NULL data:
SELECT *
FROM users
WHERE phone IS NOT NULL;
SQL's WHERE clause keeps only rows whose condition evaluates to TRUE; neither FALSE nor UNKNOWN passes the filter.
3.4 How NULL Affects Aggregate Functions
Most aggregate functions in SQL ignore NULL.
For example:
SELECT
COUNT(*) AS total_count,
COUNT(phone) AS phone_count,
AVG(age) AS average_age
FROM users;
The differences:
COUNT(*)counts the number of rows, including rows where a field is NULL.COUNT(phone)counts only rows wherephoneis non-NULL.AVG(age)computes the average of non-NULL ages.
Suppose the data is as follows:
| id | age |
|---|---|
| 1 | 20 |
| 2 | 30 |
| 3 | NULL |
Then:
COUNT(*) = 3
COUNT(age) = 2
AVG(age) = 25
Therefore, NULL in a database affects not only condition evaluation, but also aggregation, sorting, joins, and data statistics.
3.5 The Evaluation Flow of Three-Valued Logic
flowchart TD
A["Execute SQL condition expression"] --> B{"Does it involve NULL"}
B -->|"No"| C["Evaluate as TRUE or FALSE"]
B -->|"Yes"| D["Evaluate with three-valued logic"]
D --> E{"Result state"}
E -->|"TRUE"| F["WHERE keeps the row"]
E -->|"FALSE"| G["WHERE excludes the row"]
E -->|"UNKNOWN"| G
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
IV. The Difference Between Null Values, Empty Strings, and Default Values
Null values are often confused with empty strings, zero values, and default values.
The difference lies in whether a valid value exists.
| Representation | Meaning | Example |
|---|---|---|
| NULL | No usable value | Phone number unknown |
| Empty string | A string exists, but its length is zero | "" |
| Numeric zero | A numeric value exists, and it is zero | 0 |
| FALSE | A boolean value exists, and it is false | false |
| Empty collection | A collection exists, but has no elements | [] |
| Default value | An initial value provided by the system or business rules | 18 |
For example:
const user = {
name: "",
age: 0,
active: false,
tags: [],
phone: null
};
These fields express different states:
name: "": the name field exists, but the string is empty.age: 0: the age value is zero.active: false: the status is explicitly no.tags: []: the tag collection exists, but has no elements.phone: null: the phone number has no usable value.
In business modeling, these states should not be casually collapsed into NULL.
Otherwise, the semantics of the original data will be lost.
V. Null Pointers and Null References
In languages that support reference types, null values often manifest as null references.
5.1 The Essence of Null References
Take Java as an example:
User user = null;
user is a reference variable, but it currently does not point to any object.
When the program executes:
user.getName();
At runtime, object members cannot be accessed through a null reference, so the following is thrown:
NullPointerException
The essence of a null pointer exception is this: the program attempts to access an object or perform related operations through a reference that does not point to a valid object.
5.2 Propagation of Null References
Null reference problems tend to propagate along the function call chain.
For example:
public String getUserName(User user) {
return user.getProfile().getName();
}
This code has several potential null locations:
usermay be null.user.getProfile()may return null.- The receiver of the
getName()call may therefore be null.
The longer the call chain, the harder it becomes to investigate null value risks.
This can be abstracted as:
flowchart TD
A["Receive User parameter"] --> B{"Is user null?"}
B -->|"Yes"| X["Null reference access risk"]
B -->|"No"| C["Call getProfile"]
C --> D{"Is profile null?"}
D -->|"Yes"| X
D -->|"No"| E["Call getName"]
E --> F["Return username"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style X fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5.3 Common Sources of Null Pointer Problems
- The object is not initialized.
- A function returns null.
- A database query finds no record.
- An external interface returns a missing field.
- An object property is set to null during runtime.
- In a concurrent environment, the state changes between checking and use.
Among these, the race condition between checking and use deserves particular attention.
if (user.getProfile() != null) {
user.getProfile().getName();
}
If the result of getProfile() may change between two calls, retrieving the result repeatedly is not necessarily safe.
A safer approach is to save the reference first:
Profile profile = user.getProfile();
if (profile != null) {
profile.getName();
}
This still requires user itself to be non-null. If the object's state may be modified concurrently, synchronization or immutability strategies must also be designed based on the specific object.
6. Basic Concepts of Optional
Optional is a type used to represent optional values.
It encapsulates the state of whether a value may or may not be present, allowing this possibility to be reflected in the type structure.
Taking Java as an example:
Optional<String> name;
This means:
- It may contain a
String. - It may also contain no value.
The core idea of Optional is:
Do not rely only on the runtime state of an ordinary reference to express absence; instead, make "possibly absent" part of the type.
6.1 The Two States of Optional
Optional<String> name1 = Optional.of("Alice");
Optional<String> name2 = Optional.empty();
The two states:
| State | Meaning |
|---|---|
| Present | There is a non-null value inside the Optional |
| Empty | There is no value inside the Optional |
Note that Java's Optional does not allow creating an empty value via Optional.of(null).
Optional<String> name = Optional.of(null);
This throws a NullPointerException.
If the value passed in may be null, you can use:
Optional<String> name = Optional.ofNullable(null);
The result is Optional.empty().
6.2 Conceptual Structure of Optional
You can think of Optional as a container with two states:
flowchart TD
A["Optional<T>"] --> B{"Contains a value?"}
B -->|"Yes"| C["Present<T>"]
B -->|"No"| D["Empty"]
C --> E["Holds a valid T"]
D --> F["Holds no value"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
From a type-design perspective, Optional can be abstracted as:
where:
Some(T)means a value of type T exists.Nonemeans no value exists.
This is the Sum Type idea from algebraic data types.
A concrete implementation of Optional does not necessarily use these two constructor names, but the type semantics it expresses are the same.
VII. Implementation and Use of Optional
7.1 Java Optional
Java 8 introduced java.util.Optional.
Common ways to create one:
Optional<String> a = Optional.of("Alice");
Optional<String> b = Optional.ofNullable(null);
Optional<String> c = Optional.empty();
Common methods:
| Method | Purpose |
|---|---|
of(value) |
Creates a non-null Optional; throws an exception if the argument is null |
ofNullable(value) |
Creates an empty Optional when the argument is null |
empty() |
Creates an empty Optional |
isPresent() |
Checks whether a value is present |
isEmpty() |
Checks whether no value is present |
get() |
Gets the inner value; throws an exception when empty |
orElse(value) |
Returns a default value when empty |
orElseGet(supplier) |
Obtains a default value through a Supplier when empty |
orElseThrow() |
Throws an exception when empty |
map() |
Transforms the inner value |
flatMap() |
Transforms and flattens a nested Optional |
filter() |
Filters the inner value by a condition |
ifPresent() |
Performs an action when a value is present |
7.2 Checking For and Getting a Value
The traditional way:
String name = null;
if (name != null) {
System.out.println(name.length());
}
Using Optional:
Optional<String> name = Optional.ofNullable("Alice");
name.ifPresent(value -> {
System.out.println(value.length());
});
ifPresent only runs the callback when a value is present.
7.3 Using orElse to Provide a Default Value
Optional<String> name = Optional.empty();
String result = name.orElse("Guest");
When the Optional is empty, "Guest" is returned.
Note the difference between orElse and orElseGet:
String result1 = name.orElse(createDefaultName());
String result2 = name.orElseGet(
() -> createDefaultName()
);
The argument expression of orElse is evaluated at call time, so the argument expression is executed even when the Optional already holds a value.
orElseGet takes a Supplier, and the Supplier is only invoked when the Optional is empty.
If computing the default value involves a database query, a network request, or complex computation, orElseGet should generally be preferred.
7.4 Using map to transform the inner value
Optional<String> name = Optional.of("Alice");
Optional<Integer> length = name.map(String::length);
Execution logic:
Optional<String>
→ extract the inner value
→ execute String::length
→ wrap the result as Optional<Integer>
If the original Optional is empty, map does not execute the transformation function, and instead returns an empty Optional.
7.5 The difference between map and flatMap
This is a very important distinction when using Optional.
Suppose:
Optional<User> user;
and there is a method:
Optional<Address> getAddress(User user);
Using map:
Optional<Optional<Address>> result =
user.map(User::getAddress);
Because the mapping function itself returns an Optional, the result is a nested structure.
Using flatMap:
Optional<Address> result =
user.flatMap(User::getAddress);
flatMap unwraps the Optional returned by the mapping function, avoiding a nested Optional.
The type relationship between the two:
In simple terms:
map: transforms the inner value and automatically wraps the result.flatMap: transforms the inner value and unwraps the already-wrapped result.
7.6 Chaining Optional operations
Optional<String> city =
Optional.ofNullable(user)
.map(User::getProfile)
.map(Profile::getAddress)
.map(Address::getCity);
If any step in the chain has no value, the subsequent mapping functions are not executed, and the final result is an empty Optional.
Note, however: if a mapping function returns null, Optional.map treats the result as an empty Optional rather than returning an Optional containing null.
8. Optional and Null-Value Modeling in Other Languages
Optional is not a design idea unique to Java. Different languages express optional values through different type systems and syntax.
8.1 Rust: Option
Rust uses Option<T> from the standard library to represent a value that may or may not exist.
Conceptually, its definition is equivalent to:
enum Option<T> {
Some(T),
None,
}
For example:
let name: Option<String> = Some(String::from("Alice"));
let empty: Option<String> = None;
Rust does not allow a regular value to be used directly as a reference that may be null; Option<T> must be handled explicitly.
A common way to handle it is pattern matching:
let name = Some("Alice");
match name {
Some(value) => println!("{}", value),
None => println!("没有名字"),
}
You can also use if let:
if let Some(value) = name {
println!("{}", value);
}
Rust's Option<T> is similar in concept to Java's Optional<T>, but it imposes stronger constraints in the type system.
8.2 Kotlin: Nullable Types
Kotlin directly distinguishes nullable types from non-nullable types through its type system.
var name: String = "Alice"
var nickname: String? = null
Here:
Stringrepresents a non-null string.String?represents a string that may be null.
When accessing a nullable variable, you need to use a safe call:
val length = nickname?.length
If nickname is null, the expression result is also null.
Kotlin also provides the Elvis operator:
val displayName = nickname ?: "Guest"
When the left side is null, the default value on the right side is used.
8.3 Swift: Optional
Swift natively supports Optional:
var name: String? = "Alice"