Objects.isNull()
Checks whether a value is null; its partner nonNull() does the opposite.
Available since: Java 8
Syntax
static boolean isNull(Object obj)Parameters
| Parameter | Type | Description |
|---|---|---|
| obj | Object | The value to check. |
Return value
booleantrue if obj is null.
Examples
Handy as a method reference in streams:
void main() {
List<String> names = Arrays.asList("Anna", null, "Oleg", null);
IO.println(names.stream().filter(Objects::nonNull).toList());
IO.println(names.stream().filter(Objects::isNull).count());
}Output:
[Anna, Oleg]
2Notes
In a plain condition obj == null reads just as well. The methods exist for lambdas and method references: filter(Objects::nonNull) is shorter than filter(x -> x != null).
See also
- Objects.requireNonNull() — Checks that a value is not null and throws NullPointerException with a clear message right away.
- Objects.equals() — Compares two objects with equals(), safely for null.
Related recipes
In the tutorial
- Methods of the Object class — The toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.