Java fprintf, printf, sprintf (fscanf, scanf, sscanf)





Java scanf

Introduction to Java printf

The printf package for Java provides some powerful methods for formatting text. In this document, an introduction to formatted output of some of Java's datatype is given with help of examples. The Format class provides several static methods for formatted writing, such as fprintf, printf and sprintf. These methods are inspired and very look-a-like to the equally named methods found in the C-language. (about 1000 words)

Hello world!

We start with the classical example of writing "Hello world!" to the standard output.

import com.braju.format.*;

public class example01 {
  public static void main(String[] args) {
    Format.printf("Hello world!\n");

On line 1 we import all classes to be used, which in this case is only com.braju.format.Format. Basically, all your programs making use of the printf package will have a line like this. On line 5, is the code that writes "Hello world!". Its result is exactly the same as the code System.out.println("Hello world!"); would give. We are using a static method called printf in the Format class. The '\n' character is a system independent carriage return (this is not the case if you use that character with System.out.print).

Using a template of what to write

In the rest of the text only the code of interest will be shown and not the whole program. Assume that we have several users in a string array {"world", "Adam", "Eve", "Bill"} that we want to say hello to by printing out a message to them on the standard output. This can be done as:

String[] user = {"world", "Adam", "Eve", "Bill"};
for (int i=0; i<user.length; i++)
  Format.printf("Hello %s!\n", new Parameters(user[i]));

This code will generate the output:

Hello world!
Hello Adam!
Hello Eve!
Hello Bill!

In line 1, we set up the "database" of users, using a string array. In line 2 and 3, we are, for each user, writing "Hello " followed by the name of the user and then end with a '!' and a newline. In this example, as in most cases, the printf method takes two arguments. The first argument is a format string and the second is a list of parameters. The format string, here "Hello %s!\n", is a template of what is going to be written. A format string contains plain characters together with zero or more format flags, e.g. the %s format flag. The format flag %s tells us that this part of the template should be replaced by a string. What will be inserted is the next argument in the list of parameters. In this example the list contains only one argument, namely user[i].

Multiple format flags in one template

Consider the following code:

String[] user = {"Adam", "Eve"};
int[] age = {24, 20};
Format.printf("%s & %s are together %d years old.\n", 
  new Parameters(user[0]).add(user[1]).add(age[0]+age[1]));

This code will produce the output:

Adam & Eve are together 44 years old.

As before, we have a "database" of users, but now we also include the age of each user. This is all done in line 1 and 2. Looking at the template found on line 3, we conclude that is will take three parameters; two %s and one %d. The %d means that an integer will be used. The parameters are inserted into a Parameters object as seen on line 4. The first and second parameter are the strings user[0] and user[1], and the last is the integer age[0]+age[1]. The parameters are added to the list by subsequent calls to the add method. Since we do not need the list after the printf call, which is often the case, we do not need to have a reference to it and hence we can simply do new Parameters(...).

Writing aligned tables with given column widths

Once again, we are using a database containing the names and ages of users. We want to write them out in a nice table with the names in the first column and aligned to the left. The ages are placed in the second column and should be aligned to the right. We want the first column to have the width of eight characters and the second column to have the width ten. Here is an expected output:

Name:          Age:      
world    5000000000
Adam             24
Eve              20
Bill              5

The code that produce this output look like this (try to imagine how you would do this with the System.out.println method):

String[] user = {"world", "Adam", "Eve", "Bill"};
int[] age = {5e9, 24, 20, 5};
Format.printf("Name:          Age:\n");
for (int i=0; i<user.length; i++) {
  Format.printf("%-8s %10d\n", 
    new Parameters(user[i]).add(age[i]));

All the magic is in the template "%-8s %10d\n". The flag %-8s specifies that the string (user) should be aligned to the left (minus sign) with the width of eight characters. The flag %10d specifies that the integer (age) should be aligned to the right (default, no minus sign) with the width of ten characters.

Controlling the number of decimals for real values

The printf method provides an easy way to control the number of decimals, also referred to as the precision, when formatting a real value. One way yo format real values are by using the %f flag. precision is specified by putting a period (.) followed by the precision, e.g. %.4f gives four decimals. The width (and alignment) can of course be specified at the same time. The width part is placed directly before the period, e.g. %7.2f. Here is an example:

Format.printf("a=%6.3f, b=%.2f\n",
  new Parameters(1.2456).add(1.2456));

The output will be:

a= 1.246, b=1.25

More format flags

You have already learned about the format flags %s %d and %f, which are used for strings, integer values and real values, respectively. There are opher very useful formatting flags for other data types available. They are listed in the table below. The width can be set on all formats and also the precision where applicable.

flag corresponding parameter will be printed as
%b a binary integer, e.g. 00101001.
%c a character.
%d, %i a decimal integer.
%e,%E a scientific floating point number; e.g. 1.23e-03 (or 1.23E-03).
%f a floating point number; e.g. 0.00123.
%g,%G %e or %E is used if the exponent is less than -4 or greater than or equal to the precision; otherwise %f is used. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it. Precision specifies the maximum number of significant digits printed.
%l,%L a logical value (in lower or upper case), i.e. a boolean; e.g. true, false.
%o an octal integer, e.g. 373.
%s a string. All characters in string is printed or as many as then precision specifies, e.g. %.5s
%x,%X a hexadecimal integer in lower or upper case, e.g. fa3e.
%% To output "%" one have to put "%%" in the format string (there is no corresponding argument).


The printf method is much more powerful than the regular System.out.println method. It provides you methods to do the most wanted formatting of text, numbers etc. After using it once, you can not be without it!