In this article, we will learn about the format string in java method with the help of examples.
Format String in Java
The format string in java method returns the formatted string by given format and arguments.
The format string method of java language is like sprintf() function in c language and printf() method of java language.
Internal implementation
public static String format(String format, Object… args) {
return new Formatter().format(format, args).toString();
}
Format String in Java Syntax
There are two type of string format() method:
- public static String format(String format, Object… args)
- public static String format(Locale locale, String format, Object… args)
Parameters
format : format of the string.
args : arguments for the format string. It may be zero or more.
Returns
formatted string
Throws
NullPointerException : if format is null.
IllegalFormatException : if format is illegal or incompatible.
Format String in Java Example
Format String in Java Specifiers
Here, we are providing a format specifiers supported by the Java String.
Format Specifier | Data Type | Output |
---|---|---|
%a | floating point | Returns Hex output of floating point number. |
%b | Any type | “true” if non-null, “false” if null |
%c | character | Unicode character |
%d | integer | Decimal Integer |
%e | floating point | decimal number in scientific notation |
%f | floating point | decimal number |
%g | floating point | decimal number, possibly in scientific notation depending on precision & value. |
%h | any type | Hex String of value from hashCode() method. |
%n | none | Platform-specific line separator. |
%o | integer | Octal number |
%s | any type | String value |
%t | Date/Time | %t is prefix for Date/Time conversions. |
%x | integer | Hex String |
Other Popular Articles