Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Object.toString — an object's text representation

Object.toString returns an object's text representation. Overriding it lets you provide readable text useful for diagnostics.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public String toString()

Object.toString is a public instance method with no parameters that returns a String. Its result should describe the object concisely and readably.

The default implementation returns getClass().getName() + '@' + Integer.toHexString(hashCode()): the class name, @, and the hexadecimal hash code. This is neither a guaranteed unique identifier nor a memory address.

Override public String toString() with @Override to describe relevant state. In the example, an Object variable references a Point, so the call selects Point.toString().

Output need not remain stable over time or across JVM runs. Do not treat it as a persistent data format; avoid exposing secrets.

Examples

public class Main {
    static final class Point {
        private final int x;
        private final int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "Point[x=" + x + ", y=" + y + "]";
        }
    }

    public static void main(String[] args) {
        Object point = new Point(2, 3);
        System.out.println(point.toString());
    }
}

Result

Point[x=2, y=3]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources