TheDeveloperBlog.com


Java

Java String.format Examples: Numbers and Strings

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.


Integers, d 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.

Based on:

Java 8

Java program that uses String.format

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);
    }
}

Output

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."

Java program that pads with zeros

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);
	}
    }
}

Output

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.

Java program that uses precision

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);
    }
}

Output

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.

Index: It helps to use an index to reference the argument (like "%1") if we reuse the argument, or the references are different in order.

Opinion: I think just using "%s" when possible yields the clearest, easiest-to-read code. Keep it simple.

Java program that inserts string with format

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);
    }
}

Output

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.

Java program that reorders arguments

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);
    }
}

Output

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.

Padding

Right: To specify padding on the right (ten spaces on the right) we use -10s. The result string is 10 chars.

Left: To add padding to the left (right justify text) to 10 chars, we use 10s. No plus sign is used.

Java program that uses padding, right and left

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);
	}
    }
}

Output

cat            orange
dog             black
bird             blue
elephant         grey

Calendar. This example uses String.format with a Calendar date. We use "tB" to insert he 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.

Java that uses format, Calendar

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);
    }
}

Output

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."

Month: The uppercase "B" is along month name like February. The lowercase "b" is a short name like Feb. And "m" means the month number.

Day: 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.

Year: 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.

Java that formats months, days and years

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);
    }
}

Output

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.

Hours: 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.

Hours, 12-hour: The 12-hour clock requires the uppercase letter I in the format. With "l" we have the same thing but with no leading 0.

AM/PM: The difference between AM and PM is critical in life. With the lowercase p format code we get am and pm strings.

Java that formats hour, minute, second, AM and PM

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);
    }
}

Output

Hour: 18 06 18 6
Minute: 53
Second: 23
AM/PM: pm

Filenames. Sometimes we have a program that generates files on a regular basis (on a schedule). We can generate filenames with String.format that contain the current date and time.

Filename Date

A summary. With String.format, a format string is used to insert values (as from variables). We add punctuation and text data in between insertions.


Advanced features. With format, we can change how numbers are displayed. We can pad with zeros and change how far past the decimal place we go. This is powerful and useful.