Chapter 21. Formatted I/O with java.text

Java 1.4 and earlier have no equivalent of printf( ). Even Java 6 has no equivalent of scanf( ) . Part of the reason is that Java didn’t support the variable-length argument lists on which these functions depend until Java 5. However, the real reason Java didn’t have equivalents to C’s formatted I/O routines is a difference in philosophy. C’s printf( ), scanf( ), and related functions combine number formatting and parsing 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.

Tip

Of course, starting in version 5, Java does have variable-length argument lists and printf( ), as you saw in Chapter 7 (though scanf( ) is still missing). The printf( ) functionality introduced in Java 5 is really just a thin layer on top of the classes discussed in this chapter. To be honest, I’m not convinced this is an improvement.

More than one programmer has attempted to recreate printf( ) and scanf( ) in Java. 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:

System.out.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 $" + hours*salary); ...

Get Java I/O, 2nd Edition 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.