Often we need to compose strings from variables (like integers) and other text. String.format
is ideal here. It provides a format language to which we add variables.
To insert numbers, we can use the "d" format. We use ordinals after the initial "%" symbol, starting at 1 and increasing. This indicates which argument to insert.
This is a good first example. We add the values 10, 20 and 30 to a format string
. We specify the format string
as the first argument to format.
char
.string
containing text (number words), punctuation, and numeric values.public class Program { public static void main(String[] args) { // Call String.format with three integer codes. String result = String.format("One: %1$d Two: %2$d Three: %3$d", 10, 20, 30); System.out.println(result); } }One: 10 Two: 20 Three: 30
Many format codes can be used with String.format
. Here we pad a number with zeros on the left side. The first 0 means "pad with zeros" and the 5 means "use five digits."
public class Program { public static void main(String[] args) { for (int i = 0; i < 5; i++) { // Pad with zeros and a width of 5 chars. String result = String.format("%1$05d %2$05d", i, i + 10); System.out.println(result); } } }00000 00010 00001 00011 00002 00012 00003 00013 00004 00014
double
We can specify the precision of a double
or float
. We use the "f" to indicate a floating-point. Before this we specify ".3" to mean "three numbers after the decimal."
public class Program { public static void main(String[] args) { double number = 1.23456; // Specify precision with format. String value = String.format("Three numbers after decimal: %1$.3f", number); System.out.println(value); } }Three numbers after decimal: 1.235
Insert
stringsWe can insert a string
with the "s" format. This example shows three different syntax forms. We can specify just "%s," use the percentage sign "%," or use a "$" in between.
public class Program { public static void main(String[] args) { String first = "Marcus"; String last = "Aurelius"; // Use simple string format. String value = String.format("%s %s", first, last); System.out.println(value); // Use indexes before simple string format. value = String.format("%1s %2s", first, last); System.out.println(value); // Use $ symbol before string character. value = String.format("%1$s %2$s", first, last); System.out.println(value); } }Marcus Aurelius Marcus Aurelius Marcus Aurelius
This example uses both a string
and an integer in one format string
. It also inserts the second argument first—it uses the "%2" syntax for this.
public class Program { public static void main(String[] args) { String id = "ART1"; int number = 100; // Place the last argument first. // ... Use integer and string in same format string. String value = String.format("%2$d %1$s", id, number); System.out.println(value); } }100 ART1
Here we use right-padding and left-padding in a format string
. We can apply padding to strings, numbers or other values.
string
is 10 chars.public class Program { public static void main(String[] args) { String[] lefts = { "cat", "dog", "bird", "elephant" }; String[] rights = { "orange", "black", "blue", "grey" }; // Loop over both arrays and display paired strings. for (int i = 0; i < lefts.length; i++) { String left = lefts[i]; String right = rights[i]; // Add padding to the right. // ... Add padding to the left. String value = String.format("%1$-10s %2$10s", left, right); System.out.println(value); } } }cat orange dog black bird blue elephant grey
This example uses String.format
with a Calendar date. We use "t" and then "B" to insert the long month string
. With "t" and then "e" or "Y" we insert the day or year numbers.
string
.import java.util.Calendar; public class Program { public static void main(String[] args) { // Create a calendar with a specific date. Calendar cal = Calendar.getInstance(); cal.set(2015, 0, 15); // Format the month, day and year into a string. String result = String.format("Month: %1$tB Day: %1$te Year: %1$tY", cal); System.out.println(result); } }Month: January Day: 15 Year: 2015
This example shows various ways of formatting months, days, and years with String.format
. We specify formatting with uppercase or lowercase letters after the "t."
short
name like Feb. And "m" means the month number.short
name like Wed. The "d" is a day number.import java.util.Calendar; public class Program { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(2015, 1, 18); // Format the month. String result = String.format("Month: %1$tB %1$tb %1$tm", cal); System.out.println(result); // Format the day. result = String.format("Day: %1$tA %1$ta %1$td", cal); System.out.println(result); // Format the year. result = String.format("Year: %1$tY %1$ty %1$tj", cal); System.out.println(result); } }Month: February Feb 02 Day: Wednesday Wed 18 Year: 2015 15 049
This is starting to become confusing. Here we format hours, minutes and seconds with String.format
. Hours can be formatted in many ways.
import java.time.Instant; import java.util.Calendar; import java.util.Date; public class Program { public static void main(String[] args) { // Set time to current time. Calendar cal = Calendar.getInstance(); cal.setTime(Date.from(Instant.now())); // Format the hour. String result = String.format("Hour: %1$tH %1$tI %1$tk %1$tl", cal); System.out.println(result); // Format minute. result = String.format("Minute: %1$tM", cal); System.out.println(result); // Format the second. result = String.format("Second: %1$tS", cal); System.out.println(result); // Format the am and pm part. result = String.format("AM/PM: %1$tp", cal); System.out.println(result); } }Hour: 18 06 18 6 Minute: 53 Second: 23 AM/PM: pm
Sometimes we have a program that generates files on a regular basis (on a schedule). We can generate file names with String.format
that contain the current date and time.
With String.format
, a format string
is used to insert values (as from variables). We add punctuation and text data in between insertions.