Java record toString()
returns a string representation of the record.
“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 thejava.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.
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
toString()
methodThe following is the syntax for using toString()
method:
@Overridepublic 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.
The toString()
method can return two types of outputs:
By default, it returns the class name followed by @
and object memory address.
After overriding, it returns a string representation of an object (the object’s state or attributes), depending on our implementation.
toString()
methodIf 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.
toString()
in JavaOverriding 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@Overridepublic 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.
toString()
in JavaThere are multiple ways in which we can use toString()
in Java. Let’s review these methods and practice using them with code examples:
toString()
as a method of the object instanceThe 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 10Integer number=10;// Calling the toString() method as a function of the integer variableSystem.out.println( number.toString() );}}
toString()
methodThe 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 argumentSystem.out.println(Double.toString(11.0));// Implementing this on other datatypes//IntegerSystem.out.println(Integer.toString(12));// LongSystem.out.println(Long.toString(123213123));// BooleanSystem.out.println(Boolean.toString(false));}}
toString()
method with Java arraysThe 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 4int[] numbers = {11, 12, 13, 14};// Calling the toString() methodSystem.out.println(numbers.toString());// Calling the toString() method with arraysSystem.out.println(Arrays.toString(numbers));}}
toString()
method with Java exceptionThe 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 ArithmeticExceptionclass dividebyZeroAithmeticException extends ArithmeticException {@Override// Overriding the toString() method to provide a custom messagepublic 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());}}}
toString()
in JavaThe 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.
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
Which class does the toString()
method belong to by default in Java?
String
System
Object
Exception
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.
Haven’t found what you were looking for? Contact Us
Free Resources