BIG
DATA

JAVA

Java toString()

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

The toString method is widely implemented. It returns a string representation of the object. In general, the toString method returns a string that "textually represents" the object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

toString() is used to represent any Java Object into a meaningful string representation. It provides a simple, convenient mechanism for debugging classes during development. It's also widely used for logging, and for passing informative error messages to Exception constructors and assertions.

The toString() is a method that is defined in the java.lang.Object class and thus, every object has one, however, it prints out, for the most part, meaningless information. Since its default implementation doesn't provide much information, its always a best practice to override toString method in sub class.

By default the toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())

package corejavaguru;

public class MyClass {	
	public static void main(String[] args) {
		Car car = new Car();
		System.out.println(car);
	}
}

class Car {
	private int gear; 
	private String name;
	
	public Car() {
		this (0, "");
	}
	
	public Car(int gear, String name) {
		this.gear = gear;
		this.name = name;
	}
}

Output:

[email protected]

The above program prints car as [email protected] which is the default implementation of toString(). This output is the package name(corejavaguru) followed by class name (Car) and the hash code that represents that object. This is because internally System.out.println() calls an object's toString() method implicitly.

However, the above output is meaningless. No end user wants to know what the package name, class name or the hash code is. They will want to know what the object is, its content or what it does etc.

For example, they will want to know the car details like name and how many gears it has. For this you only have to make one change - add a toString() method and override it. Following is an modified version of the above program with a toString() method added:

package corejavaguru;

public class MyClass {	
	public static void main(String[] args) {
		Car car = new Car(6,"BMW");
		System.out.println(car);
	}
}

class Car {
	private int gear; 
	private String name;

	public Car() {
		this (0, "");
	}

	public Car(int gear, String name) {
		this.gear = gear;
		this.name = name;
	}

	@Override
	public String toString() {
		return "Manufacturer: " + name + " \nGear: " + gear;
	}

}

Output:

Manufacturer: BMW 
Gear: 6

The output is much better showing information about car in a human readable format.

So what is the use of it? Lots of. If you EVER need a String representation of any object for any purpose, toString() is the easiest way to go. It can perform any number of computations – as long as it returns a String in the end. It also makes debugging a lot easier and makes your objects easier to understand.

And if you ever need the old implementation with the addition of something new, you can always add super.toString() to the returned String.

toString() with Concatenation

Whenever we concatenate any other primitive data type, or object of other classes with a String object, toString() function or valueOf() function is called automatically to change the other object or primitive type into string, for successful concatenation. Lets see with an example:


int gear = 6;
String str = "Car has " + gear + " gears.";

Here 6 will be automatically converted into string for concatenation using valueOf() function.

When to use toString() method

In Java, toString method guarantees that an object can be represented textually.This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Objects often implement custom toString behavior so that the method actually tells you something about the object instance. For example, a Person class might override it to return "Last name, First name" while a Date class will show the date formatted according to some default setting

You use toString() when you want to concat Strings and not think about a special attribute, just provide a default one to the programmer. Like System.out.println("My car:" + car);

One of the most common situations where we use toString is when using StringBuilder to construct a String.

StringBuilder sb = new StringBuilder(str);
sb.append("foo");
sb.append("bar");
return sb.toString();

Many programmers use logging API like Log4J or java.util.Logger to print logs and often pass Object there: logger.info("Car not found : " + car) and if programmer doesn't override toString and print meaningful information like car manufacturer name, gears etc than it would be difficult to diagnose the problem.

Benefits of overriding toString method

I think most Java developers acknowledge the value of good toString() implementations. Although a toString() method won't impact logic like an equals(Object) or hashCode() method can, it can improve debugging and diagnostic efficiency. Less time spent figuring out what the object's state is means more time fixing the problem, moving onto more interesting challenges, and satisfying more client needs.

As discussed, overridden toString helps in debugging by printing meaningful information.

If you are debugging Java program in Eclipse then using watch or inspect feature to look object, toString will definitely help you.

While it isn't as important as obeying the equals and hashCode contracts, providing a good toString implementation makes your class much more pleasant to use. The toString method is automatically invoked when an object is passed to println, printf, the string concatenation operator, or assert, or printed by a debugger. Now if you’ve provided a good toString method for PhoneNumber, generating a useful diagnostic message is as easy as this:

System.out.println("Failed to connect: " + phoneNumber);

The benefits of providing a good toString method extend beyond instances of the class to objects containing references to these instances, especially collections. Which would you rather see when printing a map, "{[email protected]}" or "{Jenny=(707) 867-5309}"?