Java Objects - toString() Method
The java.util.Objects.toString() method returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.
Syntax
public static String toString(Object o, String nullDefault)
Parameters
o |
Specify an object. |
nullDefault |
Specify the string to return if the first argument is null. |
Return Value
Returns the result of calling toString on the first argument if it is not null and the second argument otherwise.
Exception
NA
Example:
In the example below, the java.util.Objects.toString() method returns a string representation of the given object.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating Objects Object obj1 = 100; Object obj2 = null; //calling toString method for objects System.out.println("obj1 is: " + Objects.toString(obj1, "It is null")); System.out.println("obj2 is: " + Objects.toString(obj2, "It is null")); } }
The output of the above code will be:
obj1 is: 100 obj2 is: It is null
❮ Java.util - Objects