| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

Formatted Output in Java

Page history last edited by Steve Sweeney 5 years, 2 months ago

Text output in Java is generally provided by two simple methods:

 

System.out.println();     // outputs text to screen and adds a new line at the end

System.out.print();     // outputs text to screen, but does not add a new line

 

These methods are usually enough for most simple output, but there are cases where more control over the output is required.  For greater control, we can use formatted printing, which is a concept available in many programming languages.

 

System.out.printf();     // formatted output

 

Even for simple output, the syntax is different.  Consider the following code, which produces identical results:

 

Unformatted Output  Formatted Output 

int x = 5;

System.out.println(x); 

int x = 5;

System.out.printf("%d", x);  

 

With formatted printing, the parameters (inside the brackets) are made up of two components: (1) the string that will be output, in quotes, and (2) the list of variables to use in the string.

 

In this case, the string is "%d".  The % sign indicates that a variable will be used, and the 'd' indicates that the value will be an integer.  The value itself comes from the list of variables, which in this case is just x (there is only one variable in the list).

 

See Formatted Output Reference for all of the different flags.

 

Once we have our flags and variables, we can start working on formatting.  The two most useful types of formatting control:

(1) the space occupied by each value, and

(2) the number of (rounded) decimal places for any fractional component

 

Flags with Formatting  Resulting Output 
%d  integer value with no formatting 
%5d

integer value at least 5 spaces wide

(more if the number if longer than 5)

%.3f decimal value with 3 decimal places
%10.3f decimal value, 3 decimal places, at least 10 wide
%n adds a new line at the end of the input, like println()

 

 

Sample Code  Output 

System.out.printf("%10d%10d%10d%n", 1, 10, 100);

System.out.printf("%10d%10d%10d%n", 100, 10, 1);

         1        10       100

       100        10         1 

System.out.printf("%f", 3.1415927); 

System.out.printf("%.4f", 3.1415927);

System.out.printf("%10.2f", 3.1415927);

3.1415927

3.1416

      3.14

System.out.printf("%10s %10s %10s", "Hello", "goodbye", "moreThan10Spaces");

     Hello    goodbye moreThan10spaces

0123456789012345678901234567890123456789

 

 

 

Comments (0)

You don't have permission to comment on this page.