Sprintf equivalent in Java
Use String.format()
for a formatted string or System.out.printf()
for formatted console output, resembling C's sprintf
.
Example with String.format()
:
For System.out.printf()
:
Both techniques yield Hey Alice, your score is: 85
, with %s
for strings and %d
for integers.
Mastering string formatting
Understanding place markers
Java employs %
, along with a format specifier, to indicate places in the string which will be replaced by variable values. Here are some common specifiers (a.k.a placeholders):
%d
for integers%f
for floating-point numbers%s
for strings%x
or%X
for hexadecimal numbers
Formatting Alignment
You can adjust the alignment and padding of your string. Here's an idea — add numbers between %
and the format specifier:
Quick formatted
method
From Java 13, we have a neat formatted
method for quick string formatting:
Complex Formatting Techniques
Power of ByteArrayOutputStream & PrintStream
For complex tasks, Java enables the combination of a PrintStream
with a ByteArrayOutputStream
. (Feel the power? Good!)
Performance Tricks
Don't stress out your strings! For frequent string manipulation, prefer using StringBuilder
over +
for concatenation. (Your CPU will thank you!)
Practical use-cases and tips
Date and Time Formatting
DateTimeFormatter
is a perfect choice when dealing with dates and times.
Locale-wise formatting
Locale-specific formatting can keep you from absurd conversions:
Efficient Conversion to Hex
A quick lookup table trick for hex conversion can save you a lot of time:
Was this article helpful?