Various Methods for Printing Java Objects: Tutorials with Examples

In this blog post, we will cover the following topics:

  • How to print the content of a Java object, with examples.
  • Printing Java objects using the toString method.
  • Displaying object content as a string.
  • Example of printing Java array objects.
  • Example of printing Java object collections.
  • Using the ToStringBuilder class to print all fields of a Java object as a string.
  • Converting a Java object to a JSON string.

A Java class is a set of properties methods and blueprint for an object. Objects are created using classes.

When troubleshooting issues during project development, it is crucial to print Java objects to the console to examine the actual values for debugging purposes. By default, if you print an object using System.out.println or logger statements, it displays the format packagename.classname@hashcode.

For example, suppose a User.java class is declared in the com.mycompany package.

package com.mycompany;
public class User {
 private String name;

 public String getName(){
   return name;
 }
 public void setName(String name){
   this.name=name
 }
}

When you print an object of the above class, the output is as follows:

com.mycompany.User@8e61f1a2

However, this output isn’t helpful for debugging object values.

So, how can you print the Java object content without seeing com.mycompany.User@8e61f1a2?

This post explores multiple ways to display Java object content.

  • Java.lang.Object toString() method

How to Print a Java Object Using the toString() Method

java.lang.Object serves as the base class for all other classes in the Java language, and each Java class inherently extends this class.

The toString() method, part of the java.lang.Object class, is automatically available in all Java classes and can be overridden in custom classes.

When you invoke the toString() method on an object, it typically outputs the format class name + @ symbol + hashcode of that class.

The following class does not provide a toString() method implementation. Instead, it calls the superclass java.lang.Object method toString():

public class Employee {

 private Integer id;
 private String name;
 public Employee(String name) {
  this.name=name;
 }
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

}
Employee emp=new Employee();
System.out.println(emp);
System.out.printl/n(emp.toString());

However, the information provided by the default toString() method is not useful for inspecting the object’s data. By default, when you print an object or use object.toString(), it displays the class along with the hash code, as shown below:

Output:

Employee@1517365b
Employee@1517365b

Printing Object Content as String using Custom toString() Method

To include specific fields when printing to the console, override the toString() method. The following example demonstrates:

  • How to override the toString() method for object printing.
  • How to print a Java object as a String object.
public class Employee {

    // Other fields and methods...

    @Override
    public String toString() {
        return "Employee(" + name + ")";
    }
}

Employee emp = new Employee();
emp.setName("kiran");

System.out.println(emp);
System.out.println(emp.toString());

Output:

kiran
kiran

By customizing the toString() method, you can control the content and format when printing the object.

Printing Java Array of Objects

When dealing with an array of multiple objects, it may not be practical to iterate through each object for debugging purposes. The following example demonstrates:

The below example explains.

The Arrays.toString() method returns a string representation of each object in a one-dimensional array. Meanwhile,

the Arrays.deepToString() method returns a string representation of each object in a multidimensional array, where array elements contain arrays of elements.

import java.util.Arrays;
public class EmployeeTest {

 public static void main(String[] args) {
  Employee[] emps = { new Employee("Kiran"), new Employee("John") };
  System.out.println("java Array of  Object print example");
  System.out.println(Arrays.toString(emps));

  System.out.println("java multi dimensional Array of Objects print example");
  Employee[][] emps1 = new Employee[2][2];
  emps1[0][0] = new Employee("one");
  emps1[0][1] = new Employee("two");
  emps1[1][0] = new Employee("three");
  emps1[1][1] = new Employee("foour");
  System.out.println(Arrays.deepToString(emps1));
 }

}

Output:

java Array of  Object print example
[Employee(Kiran), Employee(John)]
java multi-dimensional Array of Objects print example
[[Employee(one), Employee(two)], [Employee(three), Employee(foour)]]

This example shows how to efficiently print arrays of objects for debugging purposes.

Java Object Collection Print Example

Collections such as Set, Map, and List can be printed to the console by invoking the toString() method on each element. The following example illustrates:

  • Printing an ArrayList of objects to the console.
  • Printing a Set of objects to the console.
  • Printing a Map of objects to the console.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class EmployeeTest {

 public static void main(String[] args) {

  System.out.println("java ArrayList of Objects print example");
  List empList = new ArrayList<>();
  empList.add(new Employee("one"));
  empList.add(new Employee("two"));
  System.out.println(empList);

  System.out.println("java Set of Objects print example");
  Set empSet = new HashSet<>();
  empSet.add(new Employee("three"));
  empSet.add(new Employee("four"));
  System.out.println(empSet);

  System.out.println("java Map of Objects print example");
  Map empMap = new HashMap();
  empMap.put(1, new Employee("five"));
  empMap.put(2, new Employee("six"));
  System.out.println(empMap);
 }

}

output:

java ArrayList of Objects print example
[Employee(one), Employee(two)]
java Set of Objects print example
[Employee(three), Employee(four)]
java Map of Objects print example
{1=Employee(five), 2=Employee(six)}

ToStringBuilder Class - Print All Fields of a Java Object as a String

The ToStringBuilder class is defined in the Apache Commons Lang library. The ToStringBuilder.reflectionToString method prints all fields of a Java object as a string.

Use ToStringStyle.SHORT_PREFIX_STYLE for regular string representation ToStringStyle.JSON_STYLE for JSON string representation.

The following examples illustrate:

The following examples illustrate:

  • How to print all fields of a Java object as a string (ToStringStyle.SHORT_PREFIX_STYLE).
  • How to print a Java object as a JSON string (ToStringStyle.JSON_STYLE).
public class Employee {

 @Override
  public String toString () {
     return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);
   }

  public String toJson () {
     return ToStringBuilder.reflectionToString(this,ToStringStyle.JSON_STYLE);
   }
}
Employee emp = new Employee("one");
System.out.println(emp.toString());
System.out.println(emp.toJson());

Output

Employee[name=Kiran,id=1]
  {"name": "Kiran", "id": 1}

How to Print a Java Object as a JSON String

In this example, we convert a Java object into a JSON string using the Jackson library.

Jackson is a serialization and deserialization library for converting Java objects to/from JSON objects.

Ensure your project includes the following jar files as dependencies:

  • jackson-core
  • jackson-annotations
  • jackson-databind

If your project uses Maven, configure the dependencies as follows:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.13.0-rc2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.13.0-rc2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0-rc2</version>
</dependency>
public class Employee {

 private Integer id;
 private String name;
 public Employee(String name) {
  this.name=name;
 }
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

}

Jackson has an ObjectMapper class which provides reading and writing a json string from an object.

import com.fasterxml.jackson.databind.ObjectMapper;

public class PrintObjectAsJSOn {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setId(1);
        emp.setName("John");

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(emp);
            System.out.println(json);
        } catch (Exception e) {
                        System.out.println("An error to convert object to json");

        }
    }
}

It prints the json string

{"id":1,"name":"john"}

Conclusion

In Summary,

  • Explained printing collections like ArrayList, Set, and Map using the toString() method.
  • Use ToStringBuilder from Apache Commons Lang to print all fields of a Java object, both in regular and JSON string representation.
  • use the Jackson library to convert a Java object into a JSON string, offering powerful serialization and deserialization.