Java Reference ยท Types and Literals
The null reference
Reference for Java null: what the null literal means, where it appears, how NullPointerException happens, helpful messages, Objects utilities and Optional.
null is a literal meaning "no object". It can be assigned to any reference type but never to a primitive, and it is the default value of every reference field and array element. Calling a method or reading a field through a null reference throws NullPointerException (NPE), the most common runtime exception in Java.
Null has a few rules worth memorizing: null == null is true, x instanceof T is false when x is null, string concatenation turns it into the text "null", and a switch on a null selector throws unless the switch has an explicit case null.
String name = null; if (name != null && !name.isEmpty()) { ... }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Type variable = null; if (variable == null) { ... } Objects.requireNonNull(value, "message");
| Tool | Purpose |
|---|---|
Objects.requireNonNull(x, msg) |
Fail fast with a clear NPE. |
Objects.requireNonNullElse(x, other) |
Default when null (Java 9). |
Objects.equals(a, b) |
Null-safe equality. |
Optional.ofNullable(x) |
Wrap a possibly-null value (Java 8). |
Comparator.nullsFirst/nullsLast |
Sort lists containing null. |
case null |
Handle null in switch (Java 21). |
Usage notes
- Helpful NPE messages (default since Java 15) name the null expression, such as
Cannot invoke "String.length()" because "<local1>" is null. Variable names appear only if the code was compiled with-g; the source launcher used here shows generic names. - Never return null for collections or arrays. Return an empty list; callers then need no check.
- Use
Optionalfor return values, not for fields or parameters. - Unboxing null throws NPE:
int n = map.get(key)when the key is missing. - Concatenation:
"" + nullis"null", and so isString.valueOf((Object) null). A bareString.valueOf(null)picks thechar[]overload and throws an NPE. - Collections differ:
HashMap,ArrayListandLinkedHashMapaccept null;Map.of(),List.of(),ConcurrentHashMapandTreeMapkeys reject it. - Annotations such as
@Nullablecome from external libraries and tools; the JDK has none built in. - A
nullargument to an overloaded method may be ambiguous:print(null)withprint(String)andprint(Object)picksString, but withStringandIntegerit does not compile.