You have seen the use of the
printf()
and format()
methods to print output with formatted numbers. The String
class has an equivalent class method, format()
, that returns a String
object rather than a PrintStream
object.Using
String's
static format()
method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead ofSystem.out.printf("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar, intVar, stringVar);
you can write
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);