Thursday, August 5, 2021

How to format String in Java – String format Example

String format and printf Example
How to format String in Java is the most common problem developers encounter because of classic System.out.println() doesn’t support formatting of String while printing on console. For those who don’t know What is formatted String? here is a simple definition,  Formatted String is a String that not only displays contents but also displays it in a format that is widely accepted like including comma while displaying large numbers e.g. 100,000,000, etc. Displaying formatted String is one of the needs for modern GUI applications and thankfully Java has good support for formatting String and all other types like Integers, Double, and Date

How to format a String in Java is never as easy as it has been since Java 1.5 which along with front line features like Generics, Enum, Autoboxing and Varargs also introduce several utility methods to support rich formatting of String in Java

Prior to Java 5 java programmer relies on java.text API for all their formatting need but with Java 5 we have now two more convenient ways to format String in Java. JDK 1.5 has added format() method in java.lang.String class and provided a printf() method in PrintStream class for printing formatted output in the console.

The printf() method is similar to the C programming language printf() method and allows a programmer to print formatting string directly to console, which makes System.out.printf() better alternative to System.out.println() method. Both format() and printf()  are overloaded method to support Locale specific formatting.

By the way, this is the third article about formatting in Java, earlier we have seen Decimal Format examples and DateFormat examples for formatting numbers and dates in Java.



How String.format()or printf()works in Java

Java String format Example printf
String.format() and System.out.printf() both works similarly and if you see the signature of both methods they also accept variable arguments. Both take a minimum of two parameters, the first of them is formatting instruction, and the other was actual String or anything which needs to be formatted. Java formatting instructions are both powerful and flexible and allow you to generate formatted String in many different formats. 

It's worth to understand the format of "formatting instruction" to take full benefit of String.format() method because this is the only tricky part of String formatting especially if you have not used printf() in past.

 I have seen developers struggle to understand the formatting behavior because of a lack of knowledge of different formatting options available in Java. This is how we specify formatting instruction in Java:

String.format "%[argument number] [flags] [width] [.precision] type"

Now let's see what is the meaning of each part of formatting instruction. "%" is a special character in formatted String and it denotes the start of formatting instruction. String.format() can support multiple formatting instructions with multiple occurrences of "%" character in formatting instruction.

"argument number" is used to specify the correct argument in case multiple arguments are available for formatting. "flags" is another special formatting instruction that is used to print String in some specific format for example you can use the flag as "," to print comma on output. "width" formatting option denotes minimum number or character will be used in output but in case if a number is larger than the width then the full number will be displayed but if it's smaller in length then it will be padded with zero.

The "precision" is using for print floating point formatted String, by using precision you can specify how many decimals a floating point number will be displayed in formatted String. "type" is the only mandatory formatting option and must always come last in format String also input String which needs to be formatted must be with the same type specified in "type" parameter. 

For example, you can not input a floating point number if you have specified "type" as decimal integer "%d", that will result in an error. Now let's see an example of a String format() method to understand these formatting options better:

format ( "%,6.2f", 124.000)

In the above example of  String.format() method flag is a comma ",", width is 6 and precision is up to 2 decimal point and type is a float.


String format Example in Java

In this section, we will see different examples to format String in Java. We will see how we can format numbers and dates. Introduce decimal points and aligning number left or right etc. One of the common application of format() is to print leading zero in a number as shown in this Java program example:

/**
 * Java program to demonstrate How to format String in Java by using
 * format() method of String class and printf() method of OutputStream in Java.
 * String.format() is very powerful and not only can format String but numbers
 * and Date in Java
 *
 * @author Javin
 */

public class StringFormatExample{
 
    public static void main(String args[]){            
     
        //simple example of formatted string in Java
        //%d is used to format decimals like integers
        //position of argument is the order in which they appear in source String
          e.g here 40021 will replace the first %d and 3000 will replace the second %d.

        String formattedString = String.format("Order with OrdId : %d and Amount: %d is missing", 40021, 3000);       

      
 System.out.println(formattedString);

   
        System.out.printf("Order with OrdId : %d  and Amount: %d is missing \n", 40021, 3000);
     
        //%s is used to denote String arguments in formatted String
        String str = String.format("Hello %s", "Raj");
        System.out.println(str);
     
        //if argument is not convertible into specified data type than
 //Formatter will throw following java.util.IllegalFormatConversionException

        //e.g. specifying %d and passing 3.0
     
        //str = String.format("Number %d", 3.0);
     
//        Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
//      at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999)
//      at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709)
//      at java.util.Formatter$FormatSpecifier.print(Formatter.java:2661)
//      at java.util.Formatter.format(Formatter.java:2433)
//      at java.util.Formatter.format(Formatter.java:2367)
//      at java.lang.String.format(String.java:2769)
     
        //common meta characters used in String.format() and
 //System.out.printf() method: %s - String , %d - decimal integer

        // %f - float  %tD - date as MM/dd/yy while %td is day %tm is month
 // and %ty is 2 digit year while %tY is four digit year

     
        //Formatting date in String format method - date in MM/dd/yy
        str = String.format("Today is %tD", new Date());
        System.out.println(str);
     
        Date today = new Date();
        System.out.printf("Date in dd/mm/yy format %td/%tm/%ty %n", today,today,today );
     
        // date as July 25, 2012, difference between %td and %te is that
 // %td use leading zero while %te doesn't
        System.out.printf("Today is %tB %te, %tY %n", today,today,today,today);
     
        //adding leading zero in numbers using String format,
 //%d is for decimal, 8 specify formatted number should be 8 digits and 0 specify use
        //leading zero, default is space, so if you don't specify leading
 // character space will be used.
        System.out.printf("Amount : %08d %n" , 221);
     
        //printing positive and negative number using String format
 //+ sign for positive, - for negative and %n is for new line

        System.out.printf("positive number : +%d %n", 1534632142);
        System.out.printf("negative number : -%d %n", 989899);
     
        //printing floating point number with System.format()
        System.out.printf("%f %n", Math.E);
     
        //3 digit after decimal point
        System.out.printf("%.3f %n", Math.E);
     
        //8 charcter in width and 3 digit after decimal point
        System.out.printf("%8.3f %n", Math.E);
     
        //adding comma into long numbers
        System.out.printf("Total %,d messages processed today", 10000000);
    }
 
 
}

Output:
Order with OrdId: 40021  and Amount: 3000 is missing
Order with OrdId: 40021  and Amount: 3000 is missing
Hello Raj
Today is 07/25/12
Date in dd/mm/yy format 25/07/12
Today is July 25, 2012
Amount: 00000221
positive number: +1534632142
negative number : -989899n
2.718282
2.718
   2.718
Total 10,000,000 messages processed today


Difference between the printf and format methods in Java

printf() and format()both methods are used to format String in Java and are more or less similar. printf()is more close to the C programming language because of the identical name used in the C programming language, Anyone who has work in C previously can easily start with this printf() method also its look more like a replacement of System.out.println(). 

if you don't want to print just want a formatted string for any other purpose String format() method is a way to go. In summary, you can say that printf()writes to stdout while format() return you a formatted string.

We have already seen String format examples with both format and printf methods. In short, formatting is easier in Java and it provides several classes like DateFormat, NumberFormat, etc which can also be used to format Date and numbers.


Other Java String related posts from Javarevisited, you may like:

16 comments:

  1. I mostly use String format for left padding and displaying number in Hexadecimal and octal. it's easy to left pad any number using format method of String. Similarly you can use x or X to display number in lowercase and uppercase Hex String. You can use o to display number as octal String.

    --------------------------
    int bond = 7;
    System.out.printf("Bond, James Bond %03d %n", bond);
    System.out.printf("left paded String in Java %07d %n", bond);

    int number = 1000;
    System.out.printf("Hex equivalent of 1000 decimal is %x %n" , number);
    System.out.printf("Hexadecimal String in upper case, equivalent of 1000 decimal is %X %n" , number);

    Result:
    Bond, James Bond 007
    left padded String in Java 0000007
    Hex equivalent of 1000 decimal is 3e8
    Hexadecimal String in upper case, equivalent of 1000 decimal is 3E8
    ------------------------------

    ReplyDelete
  2. How to use String format to print Hex String?

    ReplyDelete
  3. One of the clever examples of String format method, I have seen is in toString() implementation. It's great to represent key value sort of data using format method. Here is one example, which returns a readable representation of an Item and it's price :

    @Override
    public String toString() {
    return String.format("%s =\tRs %.2f", item, price);
    }
    Output:
    Shoes = Rs 1002.12
    Bags = Rs 652.62

    ReplyDelete
  4. Is this a translated text or just plain horrible english? For some reason blogspot.com always changes to blogspot.de.. ? The content itself is very good / helpful but it's really hard to read :(

    ReplyDelete
  5. Hi Javin, your article has made me understand printf() and format() capability so well. It's really an informative article. Thanks a ton.

    ReplyDelete
  6. Hello there, I am getting below exception when trying to use printf() method and putting a tab space between two Strings, here is my code :

    System.out.printf("%s %t");


    and here is the exception
    Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 't'
    at java.util.Formatter$FormatSpecifier.(Formatter.java:2690)
    at java.util.Formatter.parse(Formatter.java:2528)
    at java.util.Formatter.format(Formatter.java:2469)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)


    Does printf() supports tab?

    ReplyDelete
  7. Getting this error, while trying to print numeric value using printf() method

    System.out.printf("%d \t", getNumericCellValue());

    Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2748)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2702)
    at java.util.Formatter.format(Formatter.java:2488)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)

    What is the problem?

    ReplyDelete
  8. To the second to last anonymous. The problem that you're having is that both String.format() and printf() take TWO arguments. The first is the syntax for organizing the text, the second is the String object itself. To correct this problem, type something like this: System.out.printf("%s%t", "This is text");

    ReplyDelete
  9. Please help (Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2748)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2702)

    ReplyDelete
  10. For Anonymous "Please help (Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String" I would assume that your "getNumericCellValue()" needs to return a double.

    ReplyDelete
  11. Just to offer my code, it does either MiB/GiB or MB/GB in Java:

    /**
    * Converts a long of bytes into a String that is human readable
    * (e.g. 347569145B becomes 331.5MiB)
    * @param bytes
    * @param siUnit - true if you want MiB (powers of 1024), false if you want MB (powers of 1000)
    * @return - String of the human readable format
    */
    private static String humanReadable(long bytes, boolean siUnit)
    {
    String[] units;
    float power;
    if (siUnit)
    {
    units = new String[]{"B", "KiB", "MiB", "GiB", "TiB"};
    power = 1024;
    }
    else
    {
    units = new String[]{"B", "KB", "MB", "GB", "TB"};
    power = 1000;
    }
    float inUnit = bytes;
    int unit = 0;
    while (inUnit >= power && unit < units.length - 1)
    {
    inUnit = inUnit / power;
    unit++;
    }

    if (unit == 0)
    {
    return String.format("%d%s", bytes, units[unit]);
    }
    else
    {
    return String.format("%.1f%s", inUnit, units[unit]);
    }
    }

    ReplyDelete
  12. public String toString()
    {
    //String.format("%-10s%8s%4f%15s%15s%10s%n"
    return String.format("%-6s%-20s%-4s%-f%-15s%-15s%-10s", origin, name, gender, age, location, alias, power);
    //origin + " " + name + " " + gender + " " + age + " " + location + " " + alias + " " + power + "\n";
    }



    what is wrong with this???

    ReplyDelete
  13. //using of int,long,double and floatting type varibles
    import java.math.*;
    import java.text.*;
    import java.util.Formatter;import java.lang.*;import java.io.PrintStream;
    class intver
    {
    public static void main(String args[]){
    double lsk;
    int is;
    int days;
    long sec;
    long distance;//declaring variables value
    is = 186282;
    days =365;
    // method start
    sec = days*24*60*60 ;//convert days in sec.
    distance = is*sec ;

    System.out.print ( "in " +days);
    String distance1 = String.format ("%,d", distance); //convert in us metric system using ,
    System.out.print( " days light will travel " +distance1);
    System.out.println( " miles per second");lsk= is*sec * 1.60984;
    String lsk1 = BigDecimal.valueOf(lsk).toPlainString();
    // String lsk2= new String.format(("##,###.##").format(Double.parseDouble(lsk)));
    // String lsk2 = String.format ("%, d", lsk);
    System.out.print("in "+days);
    System.out.printf(" days light will travel at the speed of %,d" + lsk1);
    System.out.print(" km per second") ;


    }}
    why this programme is not giving result

    ReplyDelete
  14. How to generate fixed with string in Java? for example, I want to print the String as 9 digit comma separated number, space, followed by 6 digit number. I am using following code where "," is working properly and 9 and 6 are width and "d" is for decimal but I want to print spaces for null values which is not working, any idea?

    String.format("%,9d %6d | %6d %,9d", 50000, 43, 55, 9000000);

    ReplyDelete
  15. How to add comma to a number using String format?

    ReplyDelete
  16. How to generate a fixed with String output using String.format method?

    ReplyDelete