Java String.format()
In this page:
Basic String Formatting
String.format() builds and returns a formatted String value using the same %s/%d/%f placeholder syntax as printf(), but instead of writing to the console it hands you the result to store, log, or pass along.
Example: Basic String Formatting
public class Main {
public static void main(String[] args) {
String result = String.format("%s is %d", "Alice", 30); // returned, not printed directly
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Numeric Formatting
Flags like %,d insert thousands separators (1,000,000) and %.2f controls decimal precision, letting you turn a raw double like 1234.5 into a properly formatted "1,234.50" for display.
Example: Numeric Formatting
public class Main {
public static void main(String[] args) {
String result = String.format("%,.2f", 1234.5); // "1,234.50"
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Locale-Specific Formatting
Passing a Locale (like Locale.GERMANY) as the very first argument tells String.format() to use that region's conventions -- for example, swapping the decimal comma and thousands-period used in much of Europe.
Example: Locale-Specific Formatting
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String result = String.format(Locale.GERMANY, "%,.2f", 1234.5); // "1.234,50"
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Padding and Alignment
Padding a string to a fixed width with %10s (or %-10s to left-align) is what makes columns of text -- like a receipt or a report -- line up visually even when the values are different lengths.
Example: Padding and Alignment
public class Main {
public static void main(String[] args) {
System.out.println(String.format("[%10s]", "hi")); // right-aligned, width 10
System.out.println(String.format("[%-10s]", "hi")); // left-aligned
}
}
Login to try C/C++/Java/PHP code in the editor
Reusing Arguments
Argument index syntax like %1$s lets you reference the same argument more than once, or print your arguments in a different order than you passed them, without duplicating them in the call.
Example: Reusing Arguments
public class Main {
public static void main(String[] args) {
String result = String.format("%1$s is %1$s again", "Java"); // reuses argument 1 twice
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: