What is the Java equivalent of printf (and sprintf, fprintf)?
The C language has three standard library functions (printf, sprintf, fprintf) used to write formatted output
to the standard output stream, to a string or to an arbitrary file or stream. The Java equivalent to printf (and its related methods)
is the Formatter class, along with various convenience methods such as String.format() and System.out.printf().
In fact, many C-style format strings that you might use with printf will work "out of the box" with Java System.out.printf(),
as we illustrate below.
Doing printf in Java
The printf function in C takes a format string followed by a list of arguments. The format string includes
tags that indicate where and how the arguments should be embedded in the resulting output. For example, %d indicates
a (signed) decimal integer, %x indicates a (lower-case, unsigned) hexadecimal integer and %08X indicates an upper-case hexadecimal integer
that will be left-padded with zeroes up to a width of 8 digits.
The Java equivalent of printf can be achieved in many cases simply be using the System.out.printf() method
with similar parameters. For example:
|printf("Result: %d\n", result);||System.out.printf("Result: %d%n", result);|
|printf("String: %8s\n", (str) ? str : "null");||System.out.printf("String: %8s%n", str);|
|printf("Result: %u\n", unsignedResult);||System.out.printf("Result: %d%n", result & 0xffffffffL);|
|printf("Long result: %dL\n", longRes);||System.out.printf("Result: %d%n", longRes);|
|printf("Flag: %s\n", f ? "true" : "false");||System.out.printf("Flag: %b%n", f);|
Differences between printf in C and Java
There are a few subtle differences between printf() in C and System.out.printf() in Java:
- Java provides a couple of additional specifiers, including %b for booleans and %n to insert a platform-dependent newline;
- Java is more type-tolerant than printf in C:
- there is no need to specify where a value is "long": %d will work with int or long;
%f will work with float or double etc;
- boxed equivalents such as Integer, Boolean are also allowed,
with null values handled;
- Java does not have an "unsigned decimal" formatter (arguably sensible since int and long are always signed Java);
the equivalernt of %u can be achieved with an int value by using %d and casting the int to
a long but removing the sign bit, as in the example above;
- Java's System.out.printf() is generally tolerant of null arguments (whereas passing a null pointer in C would be a little
Java's System.out.printf() also supports additional features such as configurable locale awareness and the ability
to extract different fields from a given argument (for use with dates and calendars).
Doing sprintf in Java
As a non-object oriented language, formatting a string in C requires you to allocate a buffer and then pass this
buffer as the first argument to the sprintf method.
The Java equivalent to sprintf() is String.format(). This returns a String object containing the
sprintf(str, "Result: %d", result);
|String str = String.format("Result: %d", result);|
Doing fprintf in Java
The Java equivalent to fprintf is usually to create a formatted string (e.g. using String.format())
and then print that string to the file. If the contents are relatively short, then we can create one string with all of the
required contents concatenated, then use Files.writeString() to write all of the contents in one go.
For larger files, we might use a PrintWriter wrapped around a FileWriter. As mentioned below, we could
also construct a Formatter around a file object and then call its format() method to write formatted
data to the file.
Using Formatter directly
The methods discussed above (notably System.out.println() and String.format()) are essentially
convenience methods wrapper around an instance of the Java Formatter class. The Formatter class
can also be instantiated directly. Into constructor, we pass the file or buffer that the formatted data will be
output to, and then call one of its format() methods with the format string and arguments (and optional locale
to override the default).
Java equivalents of other C/C++ features
This section contains information on other Java equivalents of C/C++ features such as malloc(), const etc.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.