Chapter 6 - Java for Beginners Course

Object String Representation

Another of the standard methods that comes from the Object class allows us to provide a String representation of our objects. This method is aptly named toString and its signature is:

public String toString();

The toString method is meant to give a human-readable representation of the object. Java will use this method internally when including the object in string concatenation operations, for example, if you do:

DictionaryEntry walk = new DictionaryEntry("walk", "definition of walk");
String result = "The object is: " + walk;

Internally, the compiler will call walk.toString() as part of the String concatenation in the second line.

The toString method shouldn’t be used to serialize/transform the object into different formats. For example, you shouldn’t use the toString method to serialize an object into JSON/XML or other formats as it isn’t meant for that purpose.

To continue with our DictionaryEntry class, we’ll use the same final class from our Object Equality sections and override the toString method:

public class DictionaryEntry {
    private final String word;

    private final String definition;

    public DictionaryEntry(String word, String definition) {
        this.word = word;
        this.definition = definition;
    }

    @Override
    public String toString() {
        return "DictionaryEntry [word=" + word + ", definition=" + definition + "]";
    }

	//...
}

Let’s give this a go:

In the example code run the JavaObjectToStringApp
DictionaryEntry walk = new DictionaryEntry("walk", "definition of walk");
String result = "The object is: " + walk;
System.out.println(result);

Output:

The object is: DictionaryEntry [word=walk, definition=definition of walk]

The default behavior of toString

If we don’t provide an override to the toString method, by default the string representation that is returned by the Object.toString method is a combination of two things:

  • The name of the class, and,

  • The hash code of the object in hexadecimal format

Both of these will be separated by an @ symbol.

For example, let’s assume we remove our toString override from our DictionaryEntry class and if we executed the same example above:

DictionaryEntry walk = new DictionaryEntry("walk", "definition of walk");
String result = "The object is: " + walk;
System.out.println(result);

Output:

The object is: io.jcoder.tutorials.ch06.objecttostring.DictionaryEntry@3791e8
The hash code you get is very likely to be different to the one we show above.

Some common usages of toString

A common usage of the toString method is when writing application logs that will help with the investigation of issues of the systems at runtime.

They’re also used to help in the debugging of applications, as it is easier to understand DictionaryEntry [word=walk, definition=definition of walk] rather than io.jcoder.tutorials.ch06.objecttostring.DictionaryEntry@3791e8.

Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations