Java Output Formatting
At times we want the output of a program to be printed in a given specific format. In the C programming language this is possible using the printf( ) function. In this section, we will discuss the different output formatting.
Let's discuss how we can format the output in Java.
There are two methods that can be used to format the output in Java:
Formatting output using System.out.printf( ) Method
The implementation of this method is very easy as it is similar to the printf( ) function in C programming.
Printing the String value : JavaTpoint Printing the integer value : x = 512 Printing the decimal value : 5.254124 Formatting the output to specific width : n = 5.2541 Formatted the output with precision : PI = 5.25 Formatted to right margin : n = 5.2541
System.out.format( ) is equivalent to printf( ) and can also be used.
An important point to note is that System.out.print( ) and System.out.println( ) take a single argument, but the printf( ) method can accept multiple arguments.
Formatting Using the DecimalFormat Class:
DecimalFormat is used to format decimal numbers.
The number is : 123.456700 Without fraction part the number is : 123 Formatted number with the specified precision is = 123.46 Appending the zeroes to the right of the number = 123.456700 Appending the zeroes to the left of the number = 00123.46 Your Formatted Income in Dollars : $550,000.79
Java String Format Specifiers
Here, we are providing a table of format specifiers supported by the Java String.