Sunday, October 28, 2018

Printing an object contents in Java without hashcode

How do I print a Java Object?


Some of you might be thinking that why should we print the contents of an object in the first place. Printing/showing the contents of an object is useful for debugging ,in the logs (if the information is not sensitive) and will be helpful in fixing some bugs as well.

The best method to show/print the contents of an object is by overriding the toString() method. If you are not going to override the toString() method and try to print the object, you will end-up seeing the hashcode of the object.
eg: Employee@7852e922

The following class is an example for overriding the toString() method.


public class Employee {
	
	private String name;
	private int id;
	private String address;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [name=");
		builder.append(name);
		builder.append(", id=");
		builder.append(id);
		builder.append(", address=");
		builder.append(address);
		builder.append("]");
		return builder.toString();
	}	
	
}


Now we are all set to show the contents of the Employee class correctly and the following class will be able to show you the contents using System.out.println

public class PrintObjectJava {

	public static void main(String[] args) {
		Employee employee = new Employee();
		employee.setName("Ravi");
		employee.setId(1);
		employee.setAddress("Philadelphia");
		
		System.out.println(employee);
	}
}

Output: Employee [name=Ravi, id=1, address=Philadelphia]

Why should we override toString() method?


All classes by default extends Object class and whenever you print object of your class, toString() method of object will be invoked and this method is going to print the hash code of your object. If our intention is to print the contents rather than the hash code of the object, we should override toString() method to print property names and thier values.

No comments:

Post a Comment