Skip to main content
Engineering LibreTexts

2.6: The toString Method

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Every object type has a method called toString that returns a string representation of the object. When you display an object using print or println, Java invokes the object’s toString method.

    By default it simply displays the type of the object and its address, but you can override this behavior by providing your own toString method. For example, here is a toString method for Time:

    public String toString() {
        return String.format("%02d:%02d:%04.1f\n",
            this.hour, this.minute, this.second);

    The definition does not have the keyword static, because it is not a static method. It is an instance method, so called because when you invoke it, you invoke it on an instance of the class (Time in this case). Instance methods are sometimes called “non-static”; you might see this term in an error message.

    The body of the method is similar to printTime in the previous section, with two changes:

    • Inside the method, we use this to refer to the current instance; that is, the object the method is invoked on.
    • Instead of printf, it uses String.format, which returns a formatted String rather than displaying it.

    Now you can call toString directly:

    Time time = new Time(11, 59, 59.9);
    String s = time.toString();

    Or you can invoke it indirectly through println:


    In this example, this in toString refers to the same object as time. The output is 11:59:59.9.

    This page titled 2.6: The toString Method is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?