Java Formatter Class
In this chapter you will learn:
Description
Formatter class outputs the formatted output.
It can format numbers, strings, and time and date.
It operates in a manner similar to the C/C++ printf()
function.
Syntax
The most commonly used format function is:
Formatter format(String fmtString, Object ... args)
Note
The fmtSring
consists characters that are copied to the output
buffer and the format specifiers.
A format specifier begins with a percent sign followed by the format conversion specifier. For example, the format specifier for floating-point data is
%f
The format specifiers and the arguments are matched in order from left to right.
Example
For example, consider this fragment:
import java.util.Formatter;
/* ww w . j ava2 s .c o m*/
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("%s gap filler %d %f", "Astring", 10, 12.3);
System.out.println(fmt.out());
}
}
The output:
In this example, the format specifiers, %s
,
%d
, and %f
,
are replaced with the arguments that follow the format string.
%s
is replaced by "Astring
",
%d
is replaced by 10
,
and %f
is replaced by 12.3
.
%s
specifies a string, and
%d
specifies an integer value.
%f
specifies a floating-point value.
All other characters are simply used as-is.
Next chapter...
What you will learn in the next chapter:
- What is Format Specifier
- What are the specifiers for Java Formatter class
- Example - Java Format Specifier
- Example - Unknown Format Conversion Exception
- How to use %n and %% specifiers to escape new line and percentage
- Example - The following code combines the %n, %d %% to display file copy progress information
Java Formatter Class
Java Format SpecifierJava Format Specifier Uppercase
Java Format Precision
Java Format Flags
Java Format Justifying Output
Java Format Negative and Positive
Java Format Line up Space
Java Format Parentheses
Java Format Zero Padding
Java Format Comma
Java Format Alternate Conversion
Java Format Argument Index
Java Format date time
Java Format Date