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));
}
}
Output234
format() method
99.990000
63
f
143
Example
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));
}
}
OutputResult is
hexadecimal: 63
Example
// 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
Number: 9,999,999
Number in German: 9.999.999
GO TO FULL VERSION