Chapter 16. Formatted I/O with java.text

One of the most obvious differences between Java and C is that Java has no equivalent of printf() or scanf() . Part of the reason is that Java doesn’t support the variable length argument lists on which these functions depend. However, the real reason Java doesn’t have equivalents to C’s formatted I/O routines is a difference in philosophy. C’s printf() and the like combine number formatting with I/O in an inflexible manner. Java separates number formatting and I/O into separate packages and by so doing produces a much more general and powerful system.

More than one programmer has attempted to recreate printf() and scanf() in Java. This task is difficult, since those functions are designed around variable length argument lists, which Java does not support. However, overloading the + signs for string concatenation is easily as effective, probably more so, since it doesn’t share the problems of mismatched argument lists. For example, which is clearer to you? This:

printf("%s worked %d hours at $%d per/hour for a total of %d dollars.\n", 
 hours, salary, hours*salary);

or this:

System.out.println(employee + " worked " + hours + " hours at $" + salary 
 + "per/hour for a total of $%d.");

I’d argue that the second is clearer. Among other advantages, it avoids problems with mismatched format strings and argument lists. (Did you notice that an argument is missing from the previous printf() statement?) On the flip side, the format string approach is a little ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.