Friday, November 21, 2025
HomeLanguagesJavaFormatter close() method in Java with Examples

Formatter close() method in Java with Examples

The close() method is a built-in method of the java.util.Formatter which closes the formatter. In case it is already closed, it will have no effect. Closing it means that it will release the resources that it is already holding.

Syntax:

public void close()

Parameters: The function accepts no parameter.

Return Value: The function returns nothing, it just closes the formatter. Hence the return type is void.

Below is the implementation of the above function:

Program 1:




// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "My name is Gopal Dave";
        frmt.format("What is your name? \n%s !",
                    name);
  
        // Print the Formatted string
        System.out.println(frmt);
  
        // Prints the formatted string
        // again since it is not closed
        System.out.println(frmt);
  
        // close the frmt
        frmt.close();
    }
}


Output:

What is your name? 
My name is Gopal Dave !
What is your name? 
My name is Gopal Dave !

Program 2:




// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer
            = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "Java programs are fun";
        frmt.format("%s !", name);
  
        System.out.println(frmt);
  
        // close the frmt
        frmt.close();
    }
}


Output:

Java programs are fun !

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#close()

RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6783 POSTS0 COMMENTS
Nicole Veronica
11929 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11999 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6863 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS