Java Objects Class Util
Java Objects Class Util
Objects
The java.util.Objects class provides various utility
methods for dealing with objects, especially related to
null handling and equality comparisons.
int fromIndex = 2;
int toIndex = 5;
int length = 4;
Objects.checkFromToIndex(fromIndex, toIndex, length);
// Throws IndexOutOfBoundsException
checkFromIndexSize(int
fromIndex, int size,
int length)
Checks if the given range starting at the specified index
with the specified size is valid for a sequence of the
specified length. Throws an
IndexOutOfBoundsException if not.
int fromIndex = 2;
int size = 5;
int length = 4;
Objects.checkFromIndexSize(fromIndex, size, length);
// Throws IndexOutOfBoundsException
requireNonNull(T obj,
Supplier<? extends X>
exceptionSupplier)
Throws a custom exception, obtained from the
provided supplier, if the object is null.
String value = null;
String result = Objects.requireNonNull(value, () -> new
IllegalArgumentException("Value cannot be null")
isNull(Object obj) &
nonNull(Object obj)
Checks if an object is null or not null, respectively.
String name = null;
if (Objects.isNull(name)) {
System.out.println("Name is null");
}