What is the Java string format() Method?
The Java string format() method is used to format strings, integers, decimal values, and so on, by using different format specifiers. This method returns the formatted string using the given locale, specified formatter, and arguments. If no locale is provided then it uses the default locale for formatting the strings. The string.format() is the static method of the Java String class.
Syntax
There are two types of string format() methods. One with provided locale and the other without it, which uses the default locale.
public static String format(Locale loc, String format, Object… args)
public static String format(String format, Object… args)
Parameters- The locale value which will be applied on format() method.
- Specifying the format of the output string.
- The number of arguments for the format string ranges from 0 to many.
- NullPointerException, if the format is null then NullPointerException is thrown.
- IllegalFormatException, if the specified format is illegal, or insufficient arguments are provided then this exception is thrown.
Format Specifiers
Let’s look at some commonly used specifiers.| Specifier | Description |
|---|---|
| %s, %S | A string formatter. |
| %d | A decimal integer, used for integers only. |
| %o | An octal integer, used for integers only. |
| %f, %F | For decimal numbers, used for floating point numbers. |
| %x, %X | A hexadecimal integer, used for integers only. |
Java String.format() Method Examples
class Main {
public static void main(String[] args) {
// Integer value
System.out.println(String.format("%d", 234));
// String value
System.out.println(String.format("%s", "format() method"));
// Float value
System.out.println(String.format("%f", 99.99));
// Hexadecimal value
System.out.println(String.format("%x", 99));
// Char value
System.out.println(String.format("%c", 'f'));
// Octal value
System.out.println(String.format("%o", 99));
}
}
Output
class Main {
public static void main(String[] args) {
int n1 = 99;
// using two different specifiers for formatting the string
System.out.println(String.format("%s\nhexadecimal: %x", "Result is", n1));
}
}
Output
// to use Locale
import java.util.Locale;
class Main {
public static void main(String[] args) {
int number = 9999999;
// using the default locale if none specified
System.out.println(String.format("Number: %,d", number););
// using the GERMAN locale as the first argument
System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
}
}
Output
Variety of Parameter Values
The String.format() method supports a wide range of format specifiers, allowing for precise control over how values are displayed. Here is an overview of commonly used specifiers:
Basic Format Specifiers
%d: Formats integers (e.g., 42).%s: Formats strings (e.g., "Hello").%f: Formats floating-point numbers (e.g., 3.14159).%b: Formats boolean values (trueorfalse).%c: Formats a single character (e.g., 'A').
Advanced Format Specifiers
%e: Formats numbers in scientific notation (e.g., 1.23e+03).%x,%X: Formats integers as hexadecimal (e.g.,0x2a).%o: Formats integers as octal (e.g.,052).%t: Formats date and time values. Requires an additional specifier such as%tYfor the year or%tHfor hours.
Example:
public class FormatExample {
public static void main(String[] args) {
int number = 42;
double pi = 3.14159;
boolean isAvailable = true;
char initial = 'J';
System.out.println(String.format("Integer: %d", number));
System.out.println(String.format("Float: %.2f", pi));
System.out.println(String.format("Boolean: %b", isAvailable));
System.out.println(String.format("Character: %c", initial));
}
}
Output:
Integer: 42 Float: 3.14 Boolean: true Character: J
Parameter Values and Their Effects on Output
The way parameters are used with String.format() significantly affects the output format. Here are some key considerations:
Width and Precision
Width specifies the minimum number of characters to be used for the output, and precision controls the number of decimal places for floating-point values or the maximum length of a string.
Examples:
System.out.println(String.format("|%10d|", 42)); // Right-align with 10 spaces
System.out.println(String.format("|%-10d|", 42)); // Left-align with 10 spaces
System.out.println(String.format("|%.3f|", 3.14159)); // 3 decimal places
Output:
| 42| |42 | |3.142|
Scientific Notation
Scientific notation is useful for representing very large or very small numbers in a concise format:
System.out.println(String.format("%e", 123456.789)); // Default scientific notation
System.out.println(String.format("%.2e", 123456.789)); // 2 decimal places
Output:
1.234568e+05 1.23e+05
Date and Time Formatting
Date and time specifiers allow precise formatting of Date objects. Use %t followed by a specific character:
%tY: Year (e.g., 2024).%tm: Month (e.g., 04).%td: Day (e.g., 01).%tH: Hour (24-hour format).%tM: Minute.%tS: Second.
Example:
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
Date now = new Date();
System.out.println(String.format("Current Date: %tY-%tm-%td", now, now, now));
System.out.println(String.format("Current Time: %tH:%tM:%tS", now, now, now));
}
}
Output:
Current Date: 2024-04-01 Current Time: 14:35:50To reinforce what you learned, we suggest you watch a video lesson from our Java Course
The String.format() method in Java is a powerful utility for formatting strings. This guide delves into the detailed syntax of placeholders, advanced formatting techniques, and complex usage examples to help developers unlock the full potential of this method.
Detailed Explanation of Placeholder Syntax
The placeholder syntax in String.format() follows this general pattern:
%[arg$][flags][width][.precision]conversion
Components of the Syntax:
arg$: Specifies the argument index (1-based) for the placeholder. For example,%1$dreferences the first argument as an integer.flags: Modifies the output format. Common flags include:-: Left-aligns the output.+: Includes a plus or minus sign for numeric values.0: Pads numbers with leading zeros.,: Groups digits with commas.(: Encloses negative numbers in parentheses.
width: Specifies the minimum number of characters for the output..precision: Specifies the number of decimal places for floating-point values or the maximum length of a string.conversion: Defines the data type for formatting. Examples include:d: Integer.s: String.f: Floating-point.e: Scientific notation.t: Date/time.
Advanced Formatting Techniques
1. Grouping Digits
Use the , flag to group digits with commas for better readability:
System.out.println(String.format("%,d", 1234567));
Output:
1,234,567
2. Controlling Decimal Places
Use .precision to control the number of decimal places for floating-point values:
System.out.println(String.format("%.2f", 123.456));
Output:
123.46
3. Enclosing Negative Numbers in Parentheses
Use the ( flag to format negative numbers:
System.out.println(String.format("%(d", -123));
Output:
(123)
Examples of Complex Placeholder Usage
Example 1: Combining Multiple Formatting Components
System.out.println(String.format("%1$,+10.2f", 12345.678));
Explanation:
1$: Uses the first argument.,: Groups digits with commas.+: Includes a plus sign for positive numbers.10: Ensures a minimum width of 10 characters..2f: Formats as a floating-point value with 2 decimal places.
Output:
+12,345.68
Example 2: Formatting Date and Time
import java.util.Date;
System.out.println(String.format("Today is %1$td/%1$tm/%1$tY", new Date()));
Explanation:
%1$td: Day of the month.%1$tm: Month.%1$tY: Year.
Output:
Today is 01/04/2024
GO TO FULL VERSION