Home
Map
String.format ExamplesUse String.format to create strings with variables inserted in them. Handle integers and strings.
Java
This page was last reviewed on Jun 1, 2023.
Format. 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.
Integer format. 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.
And We specify, after the "$" sign that we want to insert numbers (digits) with the lowercase "d" char.
Result Format yields a composed 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
Pad with zeros. 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
Precision, 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."
Note As this example shows, the "f" format will round the number up, not truncate digits.
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 strings. We 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.
Note It helps to use an index to reference the argument (like "%1") if we reuse the argument, or the references are different in order.
Also I think just using "%s" when possible yields the clearest, easiest-to-read code. Keep it simple.
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
Argument order. 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
Padding, right and left. Here we use right-padding and left-padding in a format string. We can apply padding to strings, numbers or other values.
String Padding
Tip To specify padding on the right (ten spaces on the right) we use -10s. The result string is 10 chars.
Tip 2 To add padding to the left (right justify text) to 10 chars, we use 10s. No plus sign is used.
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
Calendar. This example uses String.format with a Calendar date. We use "tB" to insert the long month string (like January). With "te" and "tY" we insert the day and year numbers.
Calendar
Note We use the "%1" at the start of the insertion points to indicate "the first argument" after the format 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
Months, days, years. 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."
Info The uppercase "B" is along month name like February. The lowercase "b" is a short name like Feb. And "m" means the month number.
Next With "A" we use the long day name like Wednesday. With "a" we specify the short name like Wed. The "d" is a day number.
Finally An uppercase Y is the long year like 2015. A lowercase "y" is a two-digit year. A "j" is the day number in an entire year.
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
Hour, minute and second. This is starting to become confusing. Here we format hours, minutes and seconds with String.format. Hours can be formatted in many ways.
Here We use the chars "HIkl" to format hours. The H means 2-digits on the 24-hour clock. The "k" is the same as H but has no leading 0.
Note The 12-hour clock requires the uppercase letter I in the format. With "l" we have the same thing but with no leading 0.
Note 2 The difference between AM and PM is critical. With the lowercase "p" format code we get am and pm strings.
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
File names. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 1, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.