One of the most obvious differences between Java and C is that Java
has no equivalent of
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
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);
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 ...