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.