An object is considered the parent type of all datatypes. An object can contain any type of values and its data type is dependent on the type of values it contains. However, you can convert an object into a String to display data in a user-friendly format, perform random operations on data, and many more.

This guide explains the approaches to convert an object to String in Java.

How to Convert an Object to String?

Conversion of an Object into a String(combination of multiple characters) makes it immutable means you can’t alter or modify the characters of a String. There are several approaches like the “toString()” Method, String Concatenation, “valueOf()” Method, and “ToStringBuilder” class offered by Apache Commons-lang3 Library to convert an Object into a String. Let’s walk through the mentioned approaches to understand their procedure for conversion of Object to String.

Method 1: Convert an Object to a String Using the “toString()” Method

The “toString()” method is widely used to convert an Object variable into a String format. This method accepts an object of any data type and returns the same variable in “String” format. The “toString()” method has the time complexity of “O(n)” because each Object character is traversed at least once to convert into a String. 

In the following code, the objects with the “integer”, “double”, “Boolean”, and “Long” values are converted into a “String” type variable:

public class Convert {
  //Conversion to String
public static void converter( Object randObj) {
  String converted = randObj.toString();
  System.out.println("\n\tThe Type of Object value '" + converted + "' is Converted into => " + converted.getClass().getSimpleName());
}
//Objects Declaration and Initialization
public static void main( String args[] ) {
  Object object1 = 15;
  System.out.println("Provided Object value '" + object1 + "' has the Type of -> " + object1.getClass().getSimpleName());

  Object object2 = 11.94;
  System.out.println("Provided Object value '" + object2 + "' has the Type of -> " + object2.getClass().getSimpleName());
 
  Object object3 = false;
  System.out.println("Provided Object value '" + object3 + "' has the Type of -> " + object3.getClass().getSimpleName());

  Object object4 = 35067L;
  System.out.println("Provided Object value '" + object4 + "' has the Type of -> " + object4.getClass().getSimpleName());

//Passing into Custom Method for Conversion
  converter(object1);
  converter(object2);
  converter(object3);
  converter(object4);
}
}

The above code works like this:

  • First, create a custom “converter” class that accepts a single “Object” type parameter named “randObj”. Now, apply the “toString()” method on “randObj” to convert an object to a String and store the result in a “converted” variable.
  • Next, display this String type “converted” variable on the console as a result. Apply the “getClass()” and “getSimpleName()” methods to retrieve the type of this variable.
  • Inside the “main()” method, initialize multiple Objects having different data types and pass them to the “converter()” method separately.

The output confirms the conversion of multiple type Objects into String:

Method 2: Convert an Object to a String Using String Concatenation

An empty String can be concatenated with the Object type variable to convert its data type into String. This approach has the time complexity of “O(1)” because this approach takes constant time for conversion regardless of Object value. 

The above example is modified according to the String Concatenation approach like this:

public class Convert {
  //Conversion to String
public static void converter( Object randObj) {
  String converted = randObj + "";
  System.out.println("\n\tThe Type of Object value '" + converted + "' is Converted into => " + converted.getClass().getSimpleName());
}

public static void main( String args[] ) {
  Object object1 = 15;
  System.out.println("Provided Object value '" + object1 + "' has the Type of -> " + object1.getClass().getSimpleName());
  Object object2 = 11.94;
  System.out.println("Provided Object value '" + object2 + "' has the Type of -> " + object2.getClass().getSimpleName());
  Object object3 = false;
  System.out.println("Provided Object value '" + object3 + "' has the Type of -> " + object3.getClass().getSimpleName());
  Object object4 = 35067L;
  System.out.println("Provided Object value '" + object4 + "' has the Type of -> " + object4.getClass().getSimpleName());

//Passing into Custom Method for Conversion
  converter(object1);
  converter(object2);
  converter(object3);
  converter(object4);
}
}

The above code is similar to the one already described in the previous section, only the “converter()” method is modified. This method now concatenates an empty String with the received Object parameter “randObj” using the “+” operator. Then, store the generated result in a new String type variable and display it on the console.

Output

Method 3: Convert an Object to a String Using valueOf() Method

The “valueOf()” method converts the arrays, nested arrays, or variables of any data type into the String format. The targeted object to be converted is passed as an argument of this method and as a result, the converted String is returned. This method has the time complexity of “O(n)” because each character of the provided Object is traversed at least once to convert into the String type. 

Let’s modify our previously defined example to use the “valueOf()” method for the conversion of an Object to a String:

public class Convert {
  //Conversion to String
public static void converter( Object randObj) {
  String converted = String.valueOf(randObj);
  System.out.println("\n\tThe Type of Object value '" + converted + "' is Converted into => " + converted.getClass().getSimpleName());
}
public static void main( String args[] ) {
  Object object1 = 15;
  System.out.println("Provided Object value '" + object1 + "' has the Type of -> " + object1.getClass().getSimpleName());
  Object object2 = 11.94;
  System.out.println("Provided Object value '" + object2 + "' has the Type of -> " + object2.getClass().getSimpleName());
  Object object3 = false;
  System.out.println("Provided Object value '" + object3 + "' has the Type of -> " + object3.getClass().getSimpleName());
  Object object4 = 35067L;
  System.out.println("Provided Object value '" + object4 + "' has the Type of -> " + object4.getClass().getSimpleName());

  converter(object1);
  converter(object2);
  converter(object3);
  converter(object4);
}
}

The description of the above code snippet is as follows:

  • Modify the “converter()” method to pass the parametric Object “randObj” as an argument for the “String.valueOf()” method for conversion
  • Store the returned result in a String type variable named “converted”.
  • Then, apply the “getClass().getSimpleName()” methods on the “converted” to return its data type and display the result on a console.

The output confirms the conversion of an Object into a String using the “valueOf()” method:

Method 4: Convert an Object to a String Using Apache Commons-lang3 Library

The “Apache Commons-lang3” provides several classes to perform different operations in Java. To convert an Object into a String its “ToStringBuilder” class is used. This class constructor accepts an Object to convert and the style in which the converted String needs to be displayed as an argument. This styling of String is provided by the “ToStringStyle” class. 

To work with this library, insert the mentioned dependencies inside the “pom.xml” file. This “pom.xml” file is automatically created with the creation of the Maven project:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.14.0</version>
</dependency>

Once done, take a look at the below code to convert an Object into a String:

import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.builder.ToStringBuilder;
//Importing commons.lang3 Classes.
public class Convert{
private String firstName;
private int experience;

public setToList(String name, int exp) {
  this.firstName = name;
  this.experience = exp;
}
  //Conversion to String
public String toDemoStr() {
  return new ToStringBuilder(this, ToStringStyle.NO_CLASS_NAME_STYLE)
  .append(" initials", firstName)
  .append(" experience", experience)
  .toString();
  }

//Passing Object for Conversion and Retrieving the Converted Result
public static void main(String[] args) {
  Convert objData = new Convert("Micheal", 5);
  System.out.println("\nConverted Object to String is: "+ objData + " and its Type is -> " + objData.getClass().getSimpleName());

  String conv = objData.toDemoStr();
  System.out.println("\nConverted Object to String is: "+ conv + " and its Type is -> " + conv.getClass().getSimpleName());
}
}

The working of the above code is as written below:

  • First, define the “firstName” and “experience” variables of the “Convert” class using the class constructor.
  • Inside the same class, define a “toDemoStr()” method that returns a new instance of the “ToStringBuilder” class. 
  • Pass the already initialized values using the “this” keyword as the first argument. Also, pass the “ToStringStyle.NO_CLASS_NAME_STYLE” as a second argument to specify the style in which the converted String will be displayed.
  • Attach custom String type data with both class values using the “append()” method. Also, apply the “toString()” method to convert the “ToStringBuilder” Object into a String.
  • In the “main()” method, create a new object for the “Convert” class and pass the values for class attributes via its constructors. Also, display the created object values and their type on the console.
  • In the end, apply the created “toDemoStr()” method on the defined object to convert an object into a String. Store and display the returned converted String over the console along with its type.

The generated output confirms the conversion of an object to a String in a specified “NO_CLASS_NAME_STYLE” style:

Bonus Tip: Convert a JSON Object to a String in Java

The JSON Object stores the data in Key/Value pair format. To convert its data into String format utilize the “JSON”, “Gson”, and “Jackson” libraries. We are using the “Gson” library. For this purpose, we create a “Maven” project, and inside the auto-created “pom.xml” file place the below code:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>

After the insertion of specified dependencies, take a look at the below code to convert JSON Object data into String:

import com.google.gson.JsonObject;
//Importing Package required Class
public class Convert {
public static void main( String args[] ) {//Inserting JSON Date
  JsonObject JSONDummyObj = new JsonObject();
  JSONDummyObj.addProperty("game", "coc");
  JSONDummyObj.addProperty("townhall", "13");
  JSONDummyObj.addProperty("level", "215");

  System.out.println("Provided JSON Object is: "+ JSONDummyObj + " and it has the Type of -> " + JSONDummyObj.getClass().getSimpleName());

//Performing Conversion
  String provObject = JSONDummyObj.toString();
  System.out.println("\nConverted JSON Object to String is: "+ provObject + " and it has the Type of -> " + provObject.getClass().getSimpleName());
}
}

The working of the above code is as follows:

  • First, import the “JsonObject” class from the “gson” library via the “import” keyword.
  • Declare an object for the “JsonObject” class named “JSONDummyObj”. Insert the “JSON type” data into the “JSONDummyObj” object using its “addProperty()” method. 
  • Next, print the “JSONDummyObj” content and apply the “getClass()” and “getSimpleName()” methods to display its data type.
  • Now, apply the “toString()” method over the “JSONDummyObj” to convert the JSON Object into a String. Store the returned result in a String type variable “provObject”. 
  • In the end, display its content along with the data type.

The below figure confirms the conversion of JSON Object into String:

That’s all about the conversion of Object to String in Java.

Conclusion

To convert an Object to a String in Java, use built-in methods like “toString()” and “valueOf()”. The “String Concatenation” operator, or “ToStringBuilder” class offered by Apache Commons Lang3 library. The “toString()” is attached to the targeted Object and it converts an Object into a String data type. The “valueOf()” method accepts an Object as a parameter and converts its data type into a String. 

The “String Concatenation” operator joins an empty String to the Object and as a result, the type of Object converts into String. The “ToStringBuilder” class uses the “toString()” method to convert an Object into a String. It allows users to generate the converted String in a specified style like JSON or Simple format. This article has explained the approaches to convert an Object to a String in Java.