Eclipse – Generate Java toString() method quickly

The Java toString() method us used when we need a string representation of an object. This method is called when we print the object or whenever we treat it like a String. It is defined in Object class and can be overwritten to customize how the object is described.

The default format for an object is constructed by concatenating the Class name, the @ symbol, and a unique hex hash code together. The default hash code method in Object is typically implemented by converting the memory address of the object into an integer.  Therefore, a typical String representation of an object would be: demoObject@112DA82.

This is rarely what you want when getting the object as some String representation for debugging, logging etc. You generally want the variables of the object to be printed with their corresponding values. This can be achieved by overwriting the toString() method in your object.

Example:

class GPSCoordinate {

	private double longitude;
	private double latitude;

 	public ToStringDemo(int longitude, String latitude) {
		this.longitude = longitude;
		this.latitude = latitude;
	}
	public int getLogitude() {
		return longitude;
	}
	public int getLatitude() {
		return latitude;
	}
	// Custom toString() Method.
	public String toString() {
		return "Logitude=" + logitude + "\n" + "Latitude=" + latitude;
	}
}

public class ToStringDemo {

	public static void main(String args[]) {
		GPSCoordinate point = new GPSCoordinate(-33.935,18.424);
		System.out.println(point);
		String s = point + " testing";
		System.out.println(s);
	}
}

When working with larger objects or creating numerous objects at once, it can become tedious to code the toString() method. Thankfully Eclipse has a handy function to auto generate the method for you.
To create the toString method:

  • Right click either on the file, or stand somewhere within the file.
  • Select the Source option
  • Then select Generate toString()… option. This will bring up a screen to ask which variables it should include in the toString() method.
  • When the required variables have been selected simply click on the OK button and it will generate the toString() method.
Tip: Check out other Source options for more auto generation tools like generating Getter and Setter methods.
About these ads
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: