Formatter class
In this chapter you will learn:
What is Formatter class for
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.
Formatting Basics
The most commonly used format function is:
Formatter format(String fmtString, Object ... args)
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. For example, consider this fragment:
import java.util.Formatter;
//from ja v a 2 s . co 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: