Java Utility Library

Java Formatter - toString() Method



The java.util.Formatter.toString() method returns the result of invoking toString() on the destination for the output.

Syntax

public String toString()

Parameters

No parameter is required.

Return Value

Returns the result of invoking toString() on the destination for the output.

Exception

Throws FormatterClosedException, if this formatter has been closed by invoking its close() method.

Example:

The example below shows the usage of java.util.Formatter.toString() method.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a formatter object
    Formatter formatter = new Formatter();
   
    //formatting a string
    String name = "John";
    int age = 25;
    formatter.format("%s is %d years old.", name, age);

    //printing the formatted string
    System.out.println(formatter);

    //printing the formatted string
    //using toString method
    System.out.println(formatter.toString());   
  }
}

The output of the above code will be:

John is 25 years old.
John is 25 years old.

❮ Java.util - Formatter