Library contents

Java String.toString

Return the same String instance when a text-oriented API requests its string representation.

A simple example

String.toString

  1. Start with "AB" as a String
  2. Do this Ask for its string form
  3. Result "AB"
A string already represents its own text. Calling toString preserves it.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("AB".toString());
    }
}
Output
AB

Syntax

Java syntax
public String toString()
JDK 21 method signatures (1)
public String toString()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Display a course code from a generic text field

A display component receives text through a general-purpose interface. Convert or transform the supplied value at the boundary where the component needs the final printable label.

From the programCharSequence field = "CS101"
ResultCS101
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        CharSequence field = "CS101";
        System.out.println(field.toString());
    }
}
Output
CS101

The runtime object is already a String, so its content is already in the required form.

Advertisements

Check whether conversion copies a receipt label

A display helper already holds an ordinary string and is asked to convert it to text. Check what it returns so the caller understands the difference between displaying a value and making an independent copy.

Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String label = new String("paid");
        System.out.println(label.toString() == label);
    }
}
Output
true

The identity check illustrates the String contract. Use equals for ordinary text comparison.

Read a parcel sorting code

The depot scans a parcel marked NC-17. The program recovers the text of this existing string for a scanner log. What exact sequence of characters should survive?

GivenNC-17
Worked resultNC-17

What to watch for

Other CharSequence implementations have different toString behaviour. Converting a String does not copy or normalize it.

Documentation for String.toString