String.format java example

In this post we will see String.format java examples.
Format method in String returns a formatted string using the specified format string and arguments.

Params :
format – the format string
args – Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero.

The format specifiers for general, character, and numeric types have the following syntax:

String.format("%.2f", 100.22345) will return 100.22

Lets see some useful formatting types

1. Formatting String

%s – returns a String
%.2s – returns first 2 characters of the String

2. Formatting Integer

%d – returns a integer

3. Formatting Float

%f – returns float
%.3f – returns float with precision upto 3 decimal
%,2.3f – returns float with precision upto 3 decimal and separated by comma after 2 digits. (see example).

4. Formatting Date

%td – returns todays date
%tm – returns currenct month
%tY – returns current year in YYYY
%ty – returns current year in YY

String.format java example


Execption in String.format

If a format is not convertible in the given type , then an exception is thrown

If we try to convert a string to date we get the following exception

You can get more information on the format specifiers in the java docs – Here