Wednesday, August 8, 2012

How to format String in Java – String format Example

String format and printf Example
How to format String in Java is most common problem developer encounter because classic System.out.println() doesn’t support formatting of String while printing on console. For those who doesn’t  know What is formatted String ? here is a simple definition,  Formatted String is a String which not only display contents but also display it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of need for modern GUI application 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 introduces several utility method to support rich formatting of String in Java. prior to Java 5 java programmer relies java.text API for all there formatting need but with Java 5 we have now two more convenient way 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 console. printf() method is similar to C programming language printf() method and allows programmer to print formatting string directly to console, which makes System.out.printf() better alternative of 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 method they also accept variable arguments . Both take minimum two parameters, first of them is formatting instruction and other was actual String or anything which needs to be formatted. Java formatting instructions are both powerful and flexible and allows you to generate formatted String on many different format. Its worth to understand format of "formatting instruction" to take full benefit of String.format() method because this is the only tricky part of String formatting specially if you have not used printf() in past. I have seen developer struggle to understand the formatting behavior because of 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 meaning of each part of formatting instruction. "%" is a special character in formatted String and it denotes start of formatting instruction. String.format() can support multiple formatting instruction with multiple occurrence of "%" character in formatting instruction.

"argument number" is used to specify correct argument in case multiple arguments are available for formatting. "flags" is another special formatting instruction which is used to print String in some specific format for example you can use flag as "," to print comma on output. "width" formatting option denotes minimum number or character will be used in output but in case if number is larger than width then full number will be displayed but if its smaller in length then it will be be padded with zero. "precision" is using for print floating point formatted String, by using precision you can specify till how many decimal a floating point number will be displayed in formatted String. "type" is the only mandatory formatting option and must always comes last in format String also input String which needs to be formatted must be with 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 error. Now let's see an example of String format() method to understand these formatting option better:

format ( "%,6.2f", 124.000)

In above example of  String.format() method flag is comma "," , width is 6 and precision is upto 2 decimal point and type is 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 first %d and 3000 will replace 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 digit 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 more or less similar. printf()is more close to C programming language because of identical name used in  C programming language, Anyone who has work in C previously can easily start with this printf() method also its look more as 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 on stdout while format() return you a formatted string.

We have already seen String format examples with both format and printf method. 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.

String related post from Javarevisited, you may like:

10 comments :

Anonymous said...

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
------------------------------

Anonymous said...

How to use String format to print Hex String?

Jay said...

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

Anonymous said...

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 :(

Beenish Zaidi said...

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

Anonymous said...

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?

Anonymous said...

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?

Anonymous said...

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");

Anonymous said...

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)

Anonymous said...

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.

Post a Comment