Overview
String formatting offers a far more versatile method for printing and combining variables into a string. A format specifier is put where the variable is to go, with the variables listed in order at the end of the statement.
Basic Methods
System.out.print("Number: " + num);
word = "Number: " + num;
String Formatting
System.out.printf("Number: %d", num);
word = String.format("Number: %d", num);
Format Specifiers
Format specifiers indicate which type of variable is to be inserted into the string.
Format Options
Reusing Variables
One of the many advantages of using string formatting is the ability to reuse variables in the output, even when using different formatting. Consider x = 8.35 and word = "Happy":
Examples
Note: single quotes have been added to the output columns to demonstrate the width of each print command. The Code has been simplified from System.out.printf to printf to save space.
Strings
String word = "Hello";
Integers
int num = 10;
Doubles
double num = 10.3456;