Java has a utility class Objects in the java.util package for working with objects.
It consists of all static methods. Most of the methods of the Objects class deal with null values gracefully.
The following is the list of methods in the class. Their descriptions follow the list.
The following code demonstrates how to use the method from the Objects class to calculate the hash code.
import java.util.Objects; /*from ww w . j ava 2s. c o m*/ public class Main { public static void main(String[] args) { // Compute hash code for two integers, a char, and a string int hash = Objects.hash(10, 800, '\u20b9', "Hello"); System.out.println("Hash Code is " + hash); } }
The code above generates the following result.
The following code shows how to use equals method from Objects class to compare two objects.
import java.util.Objects; //from w w w.j a v a 2 s. c o m public class Main { public static void main(String[] args) { // Test for equality boolean isEqual = Objects.equals(null, null); System.out.println("null is equal to null: " + isEqual); isEqual = Objects.equals(null, "XYZ"); System.out.println("null is equal to XYZ: " + isEqual); } }
The code above generates the following result.
The following code shows how to use toString method from Objects to convert object to a String.
import java.util.Objects; /*from w w w. j a v a 2 s . co m*/ public class Main { public static void main(String[] args) { // toString() method test System.out.println("toString(null) is " + Objects.toString(null)); System.out.println("toString(null, \"XXX\") is " + Objects.toString(null, "XXX")); } }
The code above generates the following result.
The following code shows how to use requireNonNull from Objects class.
import java.time.Instant; import java.util.Objects; import java.util.function.Supplier; /* w ww . j a v a2 s. c om*/ public class Main { public static void main(String[] args) { try { printName("A"); printName(null); } catch (NullPointerException e) { System.out.println(e.getMessage()); } try { Supplier<String> messageSupplier = () -> "Name is required. Error generated on " + Instant.now(); printNameWithSuplier("asdf", messageSupplier); printNameWithSuplier(null, messageSupplier); } catch (NullPointerException e) { System.out.println(e.getMessage()); } } public static void printName(String name) { Objects.requireNonNull(name, "Name is required."); System.out.println("Name is " + name); } public static void printNameWithSuplier(String name, Supplier<String> messageSupplier) { Objects.requireNonNull(name, messageSupplier); } }
The code above generates the following result.