Java Reference Library →

String toString() method - Syntax and Examples

String toString() method - Syntax and Examples

Learn about the Java String toString() method, its syntax, purpose, return value, and how to use it with examples.

This reference explains String toString() method - Syntax and Examples through its syntax, examples and boundaries. Use the linked course lessons when the surrounding Java concepts are unfamiliar.

  1. Use this reference

    Identify the documented behavior, read a complete example and check its inputs before applying it.

String toString() method - Syntax and Examples

Introduction

The toString() method in Java is a fundamental part of the Object class and is inherited by all classes. When dealing with Strings, it might seem like there's not much to do, since you can directly concatenate strings or use other methods. However, understanding `toString()` offers powerful ways to customize how your String objects are represented as text – particularly when overriding this method in custom classes that *use* Strings.

Syntax

The basic syntax for the toString() method is quite straightforward:
public String toString()
It doesn't take any parameters and returns a `String` object.

Parameters

Parameter Description
None The toString() method does not accept any parameters.

Return Value

The toString() method returns a string representation of the object.

Examples

Example 1: Default Implementation

This example demonstrates using the default implementation of toString() for String objects. When you don't override this method, it returns a string that represents the class name and the object’s hash code.

public class DefaultToString {
    public static void main(String[] args) {
        String str = "Hello World";
        System.out.println(str.toString());
    }
} 
Hello World

In this case, the default implementation of `String`'s toString() method is called which simply returns the String itself. Therefore, printing the result gives us "Hello World".

Example 2: Overriding toString() in a Custom Class

This example shows how to override the toString() method in a custom class that uses a String internally. This allows you to control how objects of your class are represented as strings.

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person [name="+name+ "]";
    }

    public static void main(String[] args) {
        Person person = new Person("Alice");
        System.out.println(person.toString());
    }
}
Person [name=Alice]

Here, the toString() method is overridden in the Person class. Instead of returning a generic representation, it returns a string that includes the person's name within square brackets. This customized output makes debugging and logging much easier.

Example 3: toString() with StringBuilder

Java · example discussed here

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person [name="+name+ "]";
    }

    public static void main(String[] args) {
        Person person = new Person("Alice");
        System.out.println(person.toString());
    }
}

This example shows using toString() on a `StringBuilder` object. `StringBuilder` is mutable, while String is immutable. When you need to manipulate strings frequently, `StringBuilder` offers better performance.

    public class StringBuilderToString {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("This is a ");
        sb.append("StringBuilder.");

        System.out.println(sb.toString());
    }
}
This is a StringBuilder.

The toString() method on the `StringBuilder` object converts its internal character sequence into an immutable String object, which can then be printed to the console.

Using this reference

Check the example’s types, inputs and documented behavior before copying it into an application. Some APIs require external libraries, files or platform services; consult their setup notes.

Related explanations: Java Data Types - Primitive and Non-Primitive, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide.

Reference checks are optional and do not count toward course progress.

    Reference library →