Format Specifier
In this chapter you will learn:
Format specifier in details
The format()
method accepts a wide variety of format specifiers.
When an uppercase specifier is used, then letters are shown in uppercase.
Otherwise, the upper- and lowercase specifiers perform the same conversion.
The following table shows the format specifiers:
Format Specifier | Conversion Applied |
---|---|
%a %A | Floating-point hexadecimal |
%b %B | Boolean |
%c | Character |
%d | Decimal integer |
%h %H | Hash code of the argument |
%e %E | Scientific notation |
%f | Decimal floating-point |
%g %G | Uses %e or %f, whichever is shorter |
%o | Octal integer |
%n | Inserts a newline character |
%s %S | String |
%t %T | Time and date |
%x %X | Integer hexadecimal |
%% | Inserts a % sign |
If the argument doesn't match the type-checks, an IllegalFormatException
is thrown.
import java.util.Formatter;
// ja v a 2 s .c om
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.toString());
System.out.println(fmt);
}
}
The output:
You can obtain a reference to the underlying output buffer by calling out()
.
It returns a reference to an Appendable
object.
Next chapter...
What you will learn in the next chapter:
- How to format individual character and how to format string
- How to pass in two strings into the format string
Home » Java Tutorial » String