Formatting Output in Java Part 1
Unlock the power of Java's Printstream class! Learn how the printf() and format() methods let you precisely control the formatting of your output.
- 338
- times read
- ~ 2
- mins read
- 467
- words
Unlock the power of Java's Printstream class! Learn how the printf() and format() methods let you precisely control the formatting of your output. Master these essential techniques to create clean, readable code.
Introduction
Java provides some built-in methods in its standard library that are useful to specify how we want to display the information on the console or in the User Graphical Interface. You can use the System.out.println()
and System.out.print()
standard methods described in the following code snippet to display information to the end-user:
This approach works fine!
Warning
If you try to format a floating-point number using print() or println() methods, you may receive an unexpected result:
Notice that the output shows an unrounded number with many decimal places. It is uneasy to read. Fortunately, there is an elegant way to solve the problem.
PrintStream class
You have been using the println()
and print()
methods to display the output of a program. Both are methods of the PrintStream class, which belongs to a package called Java.io1 that contains some Classes related to input and output. PrintStream2 also provides methods, such as format()
and printf()
, that are useful to specify how a value should be formatted.
format()
returns a reference to the formatted string, so you must define a variable and store the referenced value in it. Then you can use the variable within the program. Instead, printf()
prints the formatted string directly to the console.
That said, over here is the syntax that both share.
The printf() and format() methods of the Java Printstream class provides control over how the values must be formatted.
Both methods admit two arguments. FormatString
represents a string that includes one or more format specifiers with some optional text. It is a placeholder for the second argument and contains instructions on how it should be formatted. ArgumentList
refers to any of the data types supported by Java. You can include one or more of them.
Conclusion
So far, we have briefly reviewed the PrintStream class of the Java programming language. The PrintStream class has two additional methods, printf()
and format()
. Both share similar arguments with which we can specify how to format a value. In the next post, we'll learn about the elements of the format specifier, along with their meanings.
Resources
Footnotes
Serie: Formatting Output with Java
- Formatting Output in Java Part 1
Mario Pérez is a Software Developer based in Colombia. He often writes about creating modern web apps with Python, Next.js, and other web tech.