Home » Java String format() method

Java String format() method

by Online Tutorials Library

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 amit singh 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 Specifier Data Type Output
%a floating point (except BigDecimal) Returns Hex output of floating point number.
%b Any type “true” if non-null, “false” if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) 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 the precision and value.
%h any type Hex String of value from hashCode() method.
%n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/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.
%x integer (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| 

You may also like