Java String format()

The java string format() method returns the formatted string by given locale, format and arguments.

If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.

The format() method of java language is like sprintf() function in c language and printf() method of java language.


Internal implementation


Signature

There are two type of string format() method:


Parameters

locale : specifies the locale to be applied on the format() method.

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.


Java String format() method example

Test it Now
name is sonoo
value is 32.334340
value is                  32.334340000000

Java String Format Specifiers

Here, we are providing a table of format specifiers supported by the Java String.

Format SpecifierData TypeOutput
%afloating point (except BigDecimal)Returns Hex output of floating point number.
%bAny type"true" if non-null, "false" if null
%ccharacterUnicode character
%dinteger (incl. byte, short, int, long, bigint)Decimal Integer
%efloating pointdecimal number in scientific notation
%ffloating pointdecimal number
%gfloating pointdecimal number, possibly in scientific notation depending on the precision and value.
%hany typeHex String of value from hashCode() method.
%nnonePlatform-specific line separator.
%ointeger (incl. byte, short, int, long, bigint)Octal number
%sany typeString value
%tDate/Time (incl. long, Calendar, Date and TemporalAccessor)%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%xinteger (incl. byte, short, int, long, bigint)

Hex string.

Java String format() Method Example 2

This method supports various data types and formats them into a string type. Let us see an example.

Test it Now
101
Amar Singh
101.000000
65
c

Java String format() Method Example 3

Apart from formatting, we can set width, padding etc. of any value. Let us see an example where we are setting width and padding for an integer value.

Test it Now
101
|       101|
|101       |
| 101|
|0000000101|




Latest Courses