How to use String.format() in Java? [duplicate]

It works same as printf() of C.

%s for String 
%d for int 
%f for float

ahead

String.format("%02d", 8)

OUTPUT: 08

String.format("%02d", 10)

OUTPUT: 10

String.format("%04d", 10)

OUTPUT: 0010

so basically, it will pad number of 0’s ahead of the expression, variable or primitive type given as the second argument, the 0’s will be padded in such a way that all digits satisfies the first argument of format method of String API.

Leave a Comment