Java toString()

toString()

The method toString() allows you to parse or represent an object in java as a string.

Table of Contents

Without toString():

public class Test {
    public static void main(String [] args) {
        City s1=new City("Berlin");
        City s2=new City("Washington");

        System.out.println(s1);
        System.out.println(s2);
    }
}
class City{
    String city;

    City(String city){
        this.city=city;
    }
}

Output:

"C:\Program Files (x86)\Java\jdk1.8.0_91\bin\java" -Didea.launcher.port=7537 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\rt.jar;C:\Users\rock\IdeaProjects\Final Project\out\production\Final Project;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain test City@140e19d City@17327b6 Process finished with exit code 0

With toString():

public class Test {
    public static void main(String [] args) {
        City s1=new City("Berlin");
        City s2=new City("Washington");

        System.out.println(s1);
        System.out.println(s2);
    }
}
class City{
    String city;

    City(String city){
        this.city=city;
    }

    public String toString(){ //overriding the toString() method
        return city;
    }
}

Output:

"C:\Program Files (x86)\Java\jdk1.8.0_91\bin\java" -Didea.launcher.port=7535 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_91\jre\lib\rt.jar;C:\Users\rock\IdeaProjects\Final Project\out\production\Final Project;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain test Berlin Washington Process finished with exit code 0

Style

Here are a few rules and pointers that should be known when using toString():

  • Always override the toString() method.
  • Provide a good toString() implementation makes your class much more pleasant to use
  • When practical, the toString() method should return all of the interesting information contained in the object.
  • Whether or not you decide to specify the format, you should clearly document your in intent in the JavaDoc. The reason why is due to the fact that toString() is always public and therefore part of the public interface. Anything that’s a part of the public interface should never change in behavior, if possible.
  • Provide programmatic access to all of the information contained in the the value returned by toString(). (i.e. don’t provide any information solely through the toString() method without making it accessible with its own dedicated method).
  • Know that toString() should not:
    • Make network requests
    • Not make new threads or wait on other threads
    • Not have changing fields

Using toString() With @Override

Whenever you are overriding methods, you want to use the @Override annotation, so that the compiler knows to warn you when you aren’t actually overriding a method- whether because you made a typo or because you’re offering a new argument overload instead of overriding an existing one.

This is how it looks, with an annotation, when overriding the toString() method:

@Override
public String toString() {
    return "This is an example.";
}

When added to the previous example, CityTest.java:

public class Test {
	public static void main(String [] args) {
		
		// Object s1 & s2 is made
        City s1 = new City("Berlin"); 
		City s2 = new City("Washington");
		
		System.out.println(s1);
		System.out.println(s2);
	}
}

class City {
	String city;
	
	City(String city) {
		this.city = city;
	}
	
	@Override // This is the Override annotation, tells you that method is overriden
	public String toString() { // Method Header
		return city;
	}
}

Notice that when using the @Override annotation, it just needs to be directly above the method header of the method that is being overridden. Although the annotation is optional, it allows a reader not familiar with the codebase to know that the method exists in the parent class. In the case of the above example program CityTest.java, you would know that the class Object (Object is is a built in class, the root of the whole Java class hierarchy. The full name of the class is java.lang.Object) is the common parent for all Java classes.

Also the @Override annotation allows for the compiler to throw a warning if you aren’t actually overriding an existing method, which can be caused by:

  • The method doesn’t exist in the parent class
  • The method name has been misspelled
  • The method return type differs from the return type of the method in the parent object
  • The parameter count and/or parameter type(s) differ from the method in the parent object
    • i.e. you overloaded the method on accident, not overrided as you wanted to.
[Source]

 

What's Your Opinion?