Java format  String with examples

The Java String format() method is used to specify a template by which we can format a string before storage to a database ,printing to the console or before feeding it as input to a web service , socket call ,API call or before displaying it to the user in a mobile screen or on a webpage. The use cases are many.

The method has two variations

public static String format(String format, Object... args)

public static String format(Locale l, String format, Object... args)

The above methods throw java.util.IllegalFormatConversionException when an argument that does not match the format specifier’s conversion is passed in.

In addition to the above methods,a similar method PrintStream printf(String format, Object... args) exists that allows formatting of Strings.PrintStream is one of the classes in the java.io package that can be used to write data in a readable form.It can also be used to add functionality to another output stream as the Stream classes extensively use the Decorator design pattern.

The printf method in Java was introduced after heavily borrowing from C’s printf method.

The first parameter ,format of type String is a string template containing format specifiers along side other static text .The second argument is a variable-arity array of arguments that are fed at the respective positions as defined in our format specifiers.

Format specifiers

They are the building blocks of how we format our arguments to make the output string dynamic as per the passed arguments.

%[argument_index$][flags][width][.precision]conversion

%-Not optional. First portion of format specifiers

argument_index= an optional integer value denoting the position of the argument to be fed into this position from the arguments list.First argument is denoted by 1$,second argument by 2$ and so on.The argument_index can be swapped to determine where the passed arguments will be placed in the final string.One argument can be passed in and be used in multiple format specifiers in the template.e.g in formatting involving date/time as demonstrated in Example 4.

flags-They are optional. Used to specify alignment behavior (- for left alignment,if not specified it defaults to right alignment) .

 0 - to zero pad a numeric value.

 , - to comma separate numbers greater than 1000.

+ - to indicate + for positive numbers and – for negative numbers.

width – The width is also optional. This specifies the minimum number of characters to appear in the output. If  the input is less than the width ,the output is padded by spaces by default. If the input is greater than the width, the input is displayed in full without truncation/alteration.

precision-Precision is also optional. This specifies the number of precision digits for floating type input. In other words it means the number of digits after the decimal point(.).

conversion –Not optional this is a placeholder for the type of input data.

Some of the most common conversion characters include

 

Conversion

Description

                            Example

Code

Output

%d

The input is formatted as decimal integer.Applies to byte, short, integer, long

  String str = String.format("Joe was position %d", 3);

        System.out.println(str)

Joe was position 3

%f

Input is formatted as floating point number.Applies to float,double

String str = String.format("Pi is  %.3f", Math.PI);

        System.out.println(str);

Pi is  3.142

%e

Input formatted as floating point number in scientific format.

String str = String.format("Pi is  %e", Math.PI);

        System.out.println(str);

Pi is  3.141593e+00

%s

Input formatted as string

String str = String.format("Java is a %s programming language", "cool");

        System.out.println(str);

Java is a cool programming language

%t,%T

Input formatted as Date(%t)/time(%T).

There are character suffixes that are used for %t and % T conversions e.g ‘H’ for %T formats hour of day in 24 hour clock ranging from 00-23 whereas ‘B’ in %t formats locale-specific full name of the month e.g December.’D’ as used in this example is a date/time suffix which formats the date as "%tm/%td/%ty".

String str = String.format("This code was written on %tD",new Date());

        System.out.println(str);

This code was written on 02/27/22

%n

Newline.Adds newline at its position

     String str = String.format("This code was %nwritten on %tD",new Date());

        System.out.println(str);

This code was

written on 02/27/22

 

Example 1 (demonstrating escaping % in format specification , argument index and precision)

package devsought;

public class StringFormat1 {

    public static void main(String... args) {

        String str = String.format("Joe was position %1$d last term. He scored %2$d marks , a subject average of  %3$.2f%%.", 3, 405, 85.345);

        System.out.println(str);

    }

}

The  above program outputs

Joe was position 3 last term. He scored 405 marks , a subject average of  85.35%.

Explanation-we have used three format specifiers as below

%1$d(for position)-at first position we are expecting a decimal integer,It could also have been written as %d

%2$d(for marks)-at second position we are expecting a decimal integer,It could also have been written as %d

%3$.2f%% (for average)-at third position ,we are expecting a floating point number with a precision of 2.We pass in 85.345 and get 85.35.We also use %% inorder to escape % as % is a special character in format specification.

Example 2(Comma separating digits greater than 1000)

package devsought;

public class StringFormat2 {

    public static void main(String... args) {

        String str = String.format("The population of New York city was approximately %,d in %d.", 8500000, 2019);

        System.out.println(str);

    }

}

The above program outputs

The population of New York city was approximately 8,500,000 in 2019.

Example 3(left alignment and right alignment specifiers)

package devsought;

public class StringFormat3 {

    public static void main(String... args) {

        String header = String.format("%-15s \t %15s \t %-15s ", "Heading One", "Heading Two", "Heading Three");
        System.out.println(header);
        String row1 = String.format("%-15s \t %15s \t %-15s ", "R1Column 1", "R1Col 2", "R1Col 3");
        System.out.println(row1);
        String row2 = String.format("%-15s \t %15s \t %-15s ", "R2Col 1", "R2Column 2", "R2Col three");
        System.out.println(row2);

    }

}

The above program outputs below

 

 

Explanation-the headers are left , right and left aligned respectively. The columns are left,right and left aligned as well.

Example 4-Date/time formatting in format String

package devsought;

import java.util.Date;

public class StringFormat4 {

    public static void main(String... args) {

String str = String.format("The date/time today is %1$tA,%1$tB %1$te %1$tY %1$Tl:%1$TM %1$Tp ", new Date());

        System.out.println(str);

    }

}

The above program outputs

The date/time today is Sunday,February 27 2022 1:59 PM

Explanation-We only have one(1) argument i.e new Date().We use this same argument by applying the argument_index 1 to all our format specifications since we are extracting different data from this argument as we process our date/time.

Date/time uses suffixes specific to date, time or date/time in order to process different components of a date and/or time.

Used above are

%1$tA-formats the date as the locale specific full name day of week e.g “Sunday”,”Tuesday”

%1$tB- formats the date as the locale specific full name day of month e.g “July”,”October”

%1$te-formats the date as day of month from 1-31.

%1$tY-formats the date as 4 digit year with leading 0’s as necessary.

%1$Tl-formats the date as hour of day,in 12 hour clock system from 1-12.

%1$TM-formats date as minute within the hour formatted as 2 digits between 00-59

%1$Tp-formats the date as locale specific morning (AM) or afternoon (PM ) marker

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.