How to use the toString() in Java

“Providing a good toString() implementation makes your class much more pleasant to use and makes systems using the class easier to debug.”— Joshua Bloch

Key takeaways

  • The toString() method is part of the java.lang.Object class and is inherited by all other Java classes.

  • By default, toString() results in the class name along with the object's hashcode in hexadecimal followed by the @ symbol.

  • Overriding the toString() method results in a meaningful string representation of an object, which improves readability and debugging.

  • Using toString() in arrays and exceptions offers tailored outputs that convey more information about these objects.

Java toString()

A Java toString() is an in-built method in the java.lang.Object class, which means every class that we create in Java automatically inherits the toString() method and returns the value given to it in the string format. Therefore, any object to which this method is applied will be returned as a string representation of the object. By default, the toString() method returned a string consisting of the class name followed by the @ symbol and the object’s hashcode in hexadecimal form.

Pet@273c92

The above output string may not be the string representation we want and may fail to convey meaningful information. To generate a meaningful and understandable string representation, we can override this method in a user-defined class, as Joshua Bloch mentions in his book:

The general contract for toString says that the returned string should be “a concise but informative representation that is easy for a person to read.” The toString contract goes on to say, “It is recommended that all subclasses override this method.” Good advice, indeed!

In this Answer, we will understand the default behavior of toString(), cover overriding toString(), and explore different ways the toString() is used in Java. These are listed as follows:

  • Calling the toString() method as a method of the object instance

  • Passing arguments to toString() method

  • Using the toString() method with Java arrays

  • Using the toString() method with Java exception handling

Syntax for toString() method

The following is the syntax for using toString() method:

@Override
public String toString() {
}

Here @Override annotation is used to override the internal implementation of the toString() method. We can add our customized logic inside the toString() method body.

Return value

The toString() method can return two types of outputs:

  1. By default, it returns the class name followed by @ and object memory address.

  2. After overriding, it returns a string representation of an object (the object’s state or attributes), depending on our implementation.

The default behavior of the toString() method

If we do not override the toString() method, the Java compiler will automatically call the pre-existing implementation of toString() and return the class name with @ and the object memory address. Let’s understand this problem with the following example:

class Pet{
String name;
Integer age;
Pet(String n, Integer a){
this.name=n;
this.age=a;
}
}
class HelloWorld {
public static void main( String args[] ) {
Pet p = new Pet("Jane",10);
System.out.println(p);
System.out.println(p.toString());
}
}

The above output demonstrates that printing p outputs the object’s hashcode values, but we actually want to print the object’s values. By overriding the toString() method, we can customize the output to show the desired values.

How to override toString() in Java

Overriding the toString() method in Java provides a clear, meaningful representation of an object’s state, which is crucial for debugging, logging, and effective integration with APIs that use the toString() method. Depending on the default implementation can lead to unclear and less useful output, making it harder to understand the object’s contents.

What is interesting is that the toString() method can easily be overridden as part of a class to cater to the user’s customized needs. The example below shows how to do this:

class Pet{
String name;
Integer age;
Pet(String n, Integer a){
this.name=n;
this.age=a;
}
//Overriding the toString() function as a class function
@Override
public String toString(){
return "The name of the pet is " + this.name + ". The age of the pet is " + this.age;
}
}
class HelloWorld {
public static void main( String args[] ) {
Pet p = new Pet("Jane",10);
//Calling the class version of toString()
System.out.println(p.toString());
}
}

In the code above, from lines 11 to 13, we have simply created a new method within the Pet class with the same name as the toString() method. On line 21, when the toString() method is called, it invokes the class version of the method.

How to use toString() in Java

There are multiple ways in which we can use toString() in Java. Let’s review these methods and practice using them with code examples:

1. Call toString() as a method of the object instance

The first way to use this function is when it is called as a method of an object instance. The example below shows this implementation:

class HelloWorld {
public static void main( String args[] ) {
//Creating an integer of value 10
Integer number=10;
// Calling the toString() method as a function of the integer variable
System.out.println( number.toString() );
}
}

2. Pass arguments to the toString() method

The second way involves calling a method from the relevant class and passing the value as an argument. The example below demonstrates this:

class HelloWorld {
public static void main( String args[] ) {
// The method is called on datatype double
// It is passed the double value as an argument
System.out.println(Double.toString(11.0));
// Implementing this on other datatypes
//Integer
System.out.println(Integer.toString(12));
// Long
System.out.println(Long.toString(123213123));
// Boolean
System.out.println(Boolean.toString(false));
}
}

3. Using the toString() method with Java arrays

The third method uses the Arrays.toString() method to print the contents of the array as calling toString() only on an array returns a hash code value. Let’s see the following example to understand the behavior of toString() with and without using Array class.

import java.util.Arrays;
class HelloWorld {
public static void main( String args[] ) {
//Creating an integer array of length 4
int[] numbers = {11, 12, 13, 14};
// Calling the toString() method
System.out.println(numbers.toString());
// Calling the toString() method with arrays
System.out.println(Arrays.toString(numbers));
}
}

4. Using the toString() method with Java exception

The toString() method is very useful in overriding Java’s exception messages to provide detailed information about exceptions. The example below demonstrates this:

// Custom exception class that extends ArithmeticException
class dividebyZeroAithmeticException extends ArithmeticException {
@Override
// Overriding the toString() method to provide a custom message
public String toString() {
return "Division by zero is not allowed.";
}
}
class HelloWorld {
public static void main(String args[]) {
try {
int result = 4 / 0;
} catch (ArithmeticException e) {
System.out.println(new dividebyZeroAithmeticException().toString());
}
}
}

Use cases of toString() in Java

The toString() method provides a way to represent an object's state or contents in the form of a string. There are various scenarios where converting an object to a string is helpful. Some of the more common use cases are listed below:

  • Logging and debugging to print an object’s state.

  • Writing to a file or reading from a file.

  • Displaying data in a user interface.

  • Analyzing data for data science purposes.

  • Converting an object to a string for sending over a network.

Advantage of Java toString()

  • Simplified code: Overriding toString() allows returning object values directly, reducing the need for additional code.

  • Customization: It allows defining custom string representations.

  • Debugging and logging: It helps include relevant details in the string format, aiding debugging and making logs more readable.

  • Implicit conversions: The official Java documentation states that if an operation, such as concatenation (+), requires a reference to be converted to a string, the conversion is done implicitly and automatically using toString().

Quiz

1

Which class does the toString() method belong to by default in Java?

A)

String

B)

System

C)

Object

D)

Exception

Question 1 of 30 attempted

In conclusion, the toString() method in Java is a fine method to create clear and useful string representations of objects. By overriding this method, developers can improve debugging, logging, and the overall readability of their code.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is Java record toString()?

Java record toString() returns a string representation of the record.


What is JavaScript tostring()?

JavaScript toString function in JavaScript is defined in the class Object. The toString() method, when called on an instance of Object (or its derived instance), returns a string representation of the instance.


What is Java map toString()?

Java Map’s toString() method generates a string representation of the map, including its keys and values.


What is Java enum toString()?

An enum in Java can be considered as an object that contains several constants. We can convert enum into the string using the toString() method.


Is toString() built-in Java?

Yes, toString() is a built-in method.


Can you use toString() on a string?

Yes, using toString() on a string simply returns the original string.


How to import toString() in Java?

In Java, there is no need to import toString() because it is automatically inherited from the Object class.


Does toString() return anything?

Yes, toString() returns a string representation of the object.


Does Java automatically use toString()?

Yes, Java automatically uses toString() when printing objects.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved