Home » Java programming language

Java Formatter format() Method with Example

Formatter Class format() method: Here, we are going to learn about the format() method of Formatter Class with its syntax and example.
Submitted by Preeti Jain, on February 14, 2020

Formatter Class format() method

Syntax:

    public Formatter format(Locale lo, String frmt, Object... args);
    public Formatter format(String frmt, Object... args);
  • format() method is available in java.util package.
  • format(Locale lo, String frmt, Object… args) method is used to return this formatter which writes formatted string to this object by the given locale(lo), string format (frmt) and the given Object argument.
  • format(String frmt, Object... args) method is used to return this formatter that writes formatted string to this object by using the given string format (frmt) and Object arguments.
  • These are the non-static methods, it is accessible with the class object and if we try to access the method with the class name then we will get an error.
  • These methods may throw an exception at the time of returning Formatter.
    • FormatterClosedException: This exception throws when this formatter close by calling it's close().
    • IllegalArgumentException: This exception when any one of the given argument is illegal or invalid format.

Parameter(s):

  • In the first case, format(Locale lo, String frmt, Object... args),
    • Locale lo – represents the locale to implement during formatting.
    • String frmt – represents the format string.
    • Object... args – represents the arguments linked by the format specifies in the format string.
  • In the first case, format(String frmt, Object... args),
    • String frmt – represents the format string.
    • Object... args – represents the arguments linked by the format specifies in the format string.

Return value:

The return type of this method is Formatter, it returns this Formatter object.

Example:

// Java program is to demonstrate the example of
// format() method of Formatter

import java.util.*;

public class FormatOfFormatter {
    public static void main(String[] args) {
        // Instantiates a StringBuffer and Formmatter object
        StringBuffer sb = new StringBuffer();
        Formatter formatt = new Formatter(sb, Locale.UK);

        // By using format(locale,format,Object...) method is
        // to format a string with the given locale
        formatt.format(Locale.UK, "Hi %s !", "IncludeHelp");

        // Display Formatted String
        System.out.println(formatt);

        // By using format(format,Object...) method is
        // to format a string with the default locale
        formatt.format("Hi %s !", "IncludeHelp");

        // Display Formatted String
        System.out.println(formatt);
    }
}

Output

Hi IncludeHelp !
Hi IncludeHelp !Hi IncludeHelp !


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.