In Java, System.out.format()
is a method used for formatted output to the console, similar to printf()
in C. It allows you to control how various data types (integers, floats, strings, etc.) are displayed, including their alignment, precision, and padding.
The
format()
method takes a format string as its first argument, followed by a variable number of arguments that correspond to the format specifiers within the string.Basic Syntax:
Key Components:
formatString
: This is aString
containing plain text and format specifiers.- Format Specifiers: These begin with a percent sign (
%
) and indicate how a corresponding argument should be formatted. Common format specifiers include:%d
: For decimal integers.%f
: For floating-point numbers.%s
: For strings.%n
: For a platform-independent newline character.
- Arguments (
arg1
,arg2
, ...): These are the values to be formatted and inserted into the output string according to the format specifiers.
Example:
Output:
Explanation of Format Specifiers in the Example:
%s: Formats the name string, %d: Formats the age integer, %.2f: Formats the salary double to two decimal places, and %n: Inserts a newline character.
Additional Formatting Options (Flags, Width, Precision):
Format specifiers can also include flags, width, and precision settings for more advanced formatting. For instance:
%5d
: Right-justifies an integer within a field of 5 characters.%-10s
: Left-justifies a string within a field of 10 characters.%05d
: Pads an integer with leading zeros to a width of 5.%,d
: Adds locale-specific group separators (e.g., commas for thousands) to an integer.
For a comprehensive list of format specifiers and options, refer to the documentation for the
java.util.Formatter
class.
No comments:
Post a Comment