toString
method?The toString
method is a static method of the Objects
class.
null
, then the method returns the result of calling the toString
method on the input object.null
, then the method returns the passed optional string the argument.To use the toString
method, import the following module:
java.util.Objects
public static String toString(Object o, String nullDefault)
Object o
: The input object.
String nullDefault
: The return value if the input object is null
.
The method returns the result of the toString
method on the first argument i.e., the input object if it is not null
. Otherwise, it returns the second argument i.e., the passed string.
public static String toString(Object o)
In the code below, we define a class Temp
with attributes a
and b
. The toString()
method is overridden in the class.
An instance of the class Temp
is passed to the method. The method should return Temp{a=2, b=3}
i.e., the value returned by toString()
method of the Temp
class.
import java.util.Objects;public class Main {static class Temp{private int a, b;public Temp(int a, int b) {this.a = a;this.b = b;}@Overridepublic String toString() {return "Temp{" +"a=" + a +", b=" + b +'}';}}public static void main(String[] args) {Temp temp = new Temp(2,3);String nullDefault = "default string";System.out.println(Objects.toString(temp, nullDefault));}}
In the code below, we define a class Temp
with attributes a
and b
. The toString()
method is overridden in the class.
A null
value and an optional string argument are passed to the method. The method should return default string
as the input object is null
.
import java.util.Objects;public class Main {static class Temp{private int a, b;public Temp(int a, int b) {this.a = a;this.b = b;}@Overridepublic String toString() {return "Temp{" +"a=" + a +", b=" + b +'}';}}public static void main(String[] args) {String nullDefault = "default string";System.out.println(Objects.toString(null, nullDefault));}}