{

Different ways to print java object tutorials with examples


In this blog post, We are going to learn the following things

  • How to print java object content for example.
  • Java object print using to String method
  • Print object content as a String
  • Java array objects print example
  • Java object collection print example
  • ToStringBuilder class - Print all fields of a java object as a string
  • Convert Java object as json string
How to print javascript object example

A Java class is a set of properties and methods and it is a blueprint for an object. An object creates using a class in java.

When an issue occurs during the development of a project, it is essential to print the java object to the console to examine the actual values for further debugging. By default, If you print an object using System.out.println or logger statements, It displays the format [email protected].

If User.java class is declared in com.mycompany,

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

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

If you print the object of the above class, The output is as follows

It isn’t going to help with object values debugging.

How do print the java object content without [email protected]?

This post covers the multiple ways to display java object content.

  • Java.lang.Object toString() method

How to print Java object using the toString() method

Java.lang.Object is the base class for all other classes in the java language, So each java class extends this class by default.

toString() is a method in the java.lang.object class that is available in all java classes by default and that you can override in custom classes.

if you call an object with the toString() method, It just gives output in the format of “name of the class + @ symbol + hashcode” of that class.

The below class is not provided toString() method implementation. It calls 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());  

This information is not useful to inspect the data of an object. By Defaults, When you print an object or object.toString() method, It always gives the class the with the hash code as below.

Output is

Overridden toString() method to include all the fields that you want to print to console. The below example explains

  • How to override toString() method to print object - toString() method
  • How to print a Java object as a String object
public class Employee {  
  
 -----------------  
@Override  
 public String toString() {  
  return "Employee("+name+")";  
 }  
}  
Employee emp=new Employee();  
 emp.setName("kiran");  
 System.out.println(emp);  
 System.out.println(emp.toString());  

Output is

kiran  
kiran  

Java array objects print example

If there are an array of multiple objects, Need to print all the objects. It looks not good to iterate each object and print for just debugging purposes.
The below example explains.

  • How to print a single array of objects - Arrays.toString() method
  • How to print a multidimensional array of objects Arrays.deepToString() method

Arrays.toString() method - returns string representation of each object in array Arrays.deepToString() method - returns a string representation of each object in the multidimensional array - Array elements contain an array 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 is

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)]]  

Java object collection print example

The collection is set, Map and List. When you are printing a collection object to the console, It will call toString() on each element.
The below example explains about

  • How to print ArrayList of objects to console
  • How to print a Set of objects to console
  • How to print a Map of objects to 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 is

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

ToStringBuilder class is defined apache commons library.
ToStringBuilder.reflectionToString method prints all fields of a java object to String using ToStringStyle.SHORT_PREFIX_STYLE, to JSon using
ToStringStyle.JSON_STYLE class.
The below examples explain about

  • How to print java object all fields as a string - toStringStyle.SHORT_PREFIX_STYLE
  • How to print java object as 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 do print java object as JSOn string

In this example, Convert a java object into a json string Jackson is a serialization and deserialization library to convert java objects from/to JSOn object

First, your project needs the following jar file as dependencies

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

if your project is using the Maven build tool, Configured the below dependencies

<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 ObjectMapper class which provides reading and writing a json string from a java 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");

        }
    }
}

And it prints the json string

{"id":1,"name":"john"}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.