Printf

Java’s printf() is a method that is used for formatting data output and is a combination of String.format() and out.print(). The types of formatting include:

  • flags
  • width
  • precision
  • conversions

General Equation: %[flag][width][.precision][conversion]

Flags: plus(+) or minus(-) sign, zero-padding, comma delimiter, and left justify.
Width: minimum amount of spaces data takes up.
Precision: amount of digits after decimal (only applies to floating points).
Conversion: decimal integer(d), floating point(f), char(c), String(s), boolean(b), and hashcode(h).

Decimal Integerbyte, short, int, long
Floating Pointfloat, double

[Example] [Example]
[Resource] [Resource]
[Resource] [Resource]


General
%c character
%C converts to uppercase character (if not already)
%d decimal integer (base 10)
%e scientific notation
%E scientific notation with a capital ‘E’
%f floating-point number
%i integer (base 10)
%b converts to boolean
%B converts to uppercase boolean
%o octal number (base 8)
%s a string of characters
%S converts to a string of uppercase characters (if not already)
%u unsigned decimal integer
%h converts to hashcode
%H converts to uppercase hashcode
%x number in hexadecimal (base 16)
%% prints a percent sign
\% prints a percent sign

Decimal Integer
%0Xd zero-fill for X digits
%Xd right justify for X digits
%-Xd left justify for X digits
%+d adds plus sign(+) to positive integers, minus sign for negative integers(-)
% d prints minus sign(-) if integer is negative, prints a space elsewise
%,d uses comma delimiter between every 3 digits (ex: 1,000)

Floating Point
%.Yf prints Y positions after decimal
%Xf takes up X spaces
%0X.Yf zero-fills
%-X.Yf left justifies

String
%Xs formats string for a minimum of X spaces
%-Xs left justify

Special Characters
\a audible alert
\b backspace
\f form feed
\n newline or linefeed
\r carriage return
\t tab
\v vertical tab
\\ backslash