What is Objects.toString in Java?

What is the toString method?

The toString method is a static method of the Objects class.

  • The method accepts an object and an optional string as arguments.
  • If the input object is not null, then the method returns the result of calling the toString method on the input object.
  • If the input object is null, then the method returns the passed optional string the argument.

To use the toString method, import the following module:

java.util.Objects

Syntax


public static String toString(Object o, String nullDefault)

Parameters

  • Object o: The input object.

  • String nullDefault: The return value if the input object is null.

Return

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.

Overloaded methods

public static String toString(Object o)

Example

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;
}
@Override
public 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;
}
@Override
public 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));
}
}

Free Resources