{"id":136,"date":"2021-01-19T19:52:20","date_gmt":"2021-01-19T19:52:20","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/?page_id=136"},"modified":"2021-01-19T21:16:37","modified_gmt":"2021-01-19T21:16:37","slug":"message-formatting","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/","title":{"rendered":"Message Formatting"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a6d4a7440b79\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a6d4a7440b79\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#The_Format_Family\" >The Format Family<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#MessageFormat\" >MessageFormat<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Explicit_Formats\" >Explicit Formats<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Using_the_setFormat_method\" >Using the setFormat method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Using_the_setFormats_method\" >Using the setFormats method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Specifying_Formats_in_the_Placeholder\" >Specifying Formats in the Placeholder<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Choice_Formats\" >Choice Formats<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Summary_of_Patterns\" >Summary of Patterns<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Summary_of_MessageFormat_Patterns\" >Summary of MessageFormat Patterns<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Summary_of_ChoiceFormat\" >Summary of ChoiceFormat<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Formatting_Numbers\" >Formatting Numbers<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Using_NumberFormat\" >Using NumberFormat<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Using_DecimalFormat\" >Using DecimalFormat<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#DecimalFormat_Example\" >DecimalFormat Example<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Using_MessageFormat\" >Using MessageFormat<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#The_printf_Family\" >The printf Family<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Classes_Involved\" >Classes Involved<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Format_Specifiers\" >Format Specifiers<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#General_Character_and_Numeric_Type_Format_Specifiers\" >General, Character and Numeric Type Format Specifiers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Date_and_Time_Format_Specifiers\" >Date and Time Format Specifiers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Non-Argument_Format_Specifiers\" >Non-Argument Format Specifiers<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Some_Examples\" >Some Examples<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Using_Plain_print_println\" >Using Plain print &amp; println<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-24\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Fixing_Some_Problems\" >Fixing Some Problems<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-25\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/i-o-files-streams\/message-formatting\/#Width_Spacing_Justification\" >Width, Spacing &amp; Justification<\/a><\/li><\/ul><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n<p class=\"wp-block-paragraph\">If you&#8217;ve used C\/C++ I\/O in the past, it may have occurred to you that C&#8217;s <code><strong>printf<\/strong><\/code> is pretty convenient for formatting output.&nbsp; So you may have asked yourself:&nbsp; &#8220;Is there anything like&nbsp;<code><strong>printf<\/strong><\/code>&nbsp;in Java?&nbsp; How do I gain greater control of formatting my output?&#8221;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Before version 5 (1.5) of Java, it wasn&#8217;t easy.&nbsp; Java provided a set of classes to allow you to format messages, but they were (and still are) not the easiest things to use.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fortunately, Java 5\/1,5 added the ability to format messages in a way that is much more compatible with C\/C++&#8217;s <strong>printf<\/strong>, that was also available in many other languages.&nbsp; It is much easier to use, and many people are already familiar with the principles of <strong>printf<\/strong> formatting.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Format_Family\"><\/span>The Format Family<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For some time, Java has provided the ability to format messages.&nbsp; It uses the following classes to achieve this functionality:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>Format<\/code><ul><li><code>MessageFormat<\/code><\/li><li><code>NumberFormat<\/code><ul><li><code>DecimalFormat<\/code><\/li><li><code>ChoiceFormat<\/code><\/li><\/ul><\/li><li><code>DateFormat<\/code><\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">These classes are part of the&nbsp;<strong>java.text<\/strong>&nbsp;package, which is primarily used for Internationalization. The subject of Internationalization (commonly called &#8220;I18N&#8221;) is a very complex one, and we won&#8217;t be covering it in detail here. Instead, we&#8217;ll just give some examples of how to do the equivalent of some <strong>printf<\/strong> operations (albeit in a more convoluted fashion).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"MessageFormat\"><\/span>MessageFormat<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><code><strong>MessageFormat<\/strong><\/code>&nbsp;provides a means to produce concatenated messages in natural language-neutral way. You use this to construct messages displayed for end users.&nbsp;&nbsp;<code><strong>MessageFormat<\/strong><\/code>&nbsp;takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2}, a {0} destroyed {1} houses and caused {3} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;hurricane&quot;, \n            new Integer(99), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which outputs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On 1\/1\/99 12:00 AM, a hurricane destroyed 99 houses and caused 100,000,000 of damage.<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Explicit_Formats\"><\/span>Explicit Formats<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We can change the way each object is displayed in the formatted string, by:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Adding placeholder information to the string itself, or<\/li><li>Calling the appropriate&nbsp;<code><strong>setFormat<\/strong><\/code>&nbsp;or&nbsp;<code><strong>setFormats<\/strong><\/code>&nbsp;method<\/li><\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_the_setFormat_method\"><\/span>Using the setFormat method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how to do it by calling&nbsp;<code><strong>setFormat<\/strong><\/code>&nbsp;methods:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.text.DateFormat;\nimport java.text.NumberFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2}, a {0} destroyed {1} houses and caused {3} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        msgFormat.setFormat(0, DateFormat.getDateInstance(DateFormat.LONG));\n        msgFormat.setFormat(3, NumberFormat.getCurrencyInstance());\n        Object&#x5B;] msgArgs =\n        { \n            &quot;hurricane&quot;, \n            new Integer(99), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On January 1, 1999, a hurricane destroyed 99 houses and caused $100,000,000.00 of damage.<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_the_setFormats_method\"><\/span>Using the setFormats method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">We could have accomplished the same thing as follows:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.text.DateFormat;\nimport java.text.Format;\nimport java.text.NumberFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2}, a {0} destroyed {1} houses and caused {3} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Format argFormats&#x5B;] =\n        {\n            DateFormat.getDateInstance(DateFormat.LONG),\n            null,\n            null,\n            NumberFormat.getCurrencyInstance()\n        };\n        msgFormat.setFormats(argFormats);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;hurricane&quot;, \n            new Integer(99), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can repeat the same argument, but with a different format:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.text.DateFormat;\nimport java.text.Format;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2}, a {0} touched down at {2} and destroyed {1} houses.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Format argFormats&#x5B;] =\n        {\n            DateFormat.getDateInstance(DateFormat.LONG),\n            null,\n            DateFormat.getTimeInstance(DateFormat.SHORT),\n            null\n        };\n        msgFormat.setFormats(argFormats);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;tornado&quot;, \n            new Integer(99), \n            new GregorianCalendar(1999, 0, 1).getTime()\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which outputs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On January 1, 1999, a tornado touched down at 12:00 AM and destroyed 99 houses.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><em>Note:<\/em><\/strong> The argument formats correspond to the position of the placeholder, while the message arguments correspond to the number of the placeholder.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Specifying_Formats_in_the_Placeholder\"><\/span>Specifying Formats in the Placeholder<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Another way of controlling the format is to specify the formats&nbsp;<em>in the placeholder itself<\/em>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2,date,long}, a {0} touched down at {2,time,short}, &quot; +\n         &quot;destroyed {1} houses, and caused {3,number,currency} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;tornado&quot;, \n            new Integer(99), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On January 1, 1999, a tornado touched down at 12:00 AM, destroyed 99 houses, and caused $100,000,000.00 of damage.<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Choice_Formats\"><\/span>Choice Formats<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Consider the following modification of the above program:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2,date,long}, a {0} &quot; +\n         &quot;destroyed {1} houses, and caused {3,number,currency} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;earthquake&quot;, \n            new Integer(1), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This outputs the string:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On January 1, 1999, a earthquake destroyed 1 houses, and caused $100,000,000.00 of damage.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">which should, to be grammatically correct, read:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On January 1, 1999, <strong>an earthquake<\/strong> destroyed <strong>1 house<\/strong>, and caused $100,000,000.00 of damage.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In other words,&nbsp;<em>we have to deal with plurals correctly<\/em>, as well as ensuring that&nbsp;<em>parts of speech match properly<\/em>&nbsp;(such as indefinite articles, etc.). This can be more important and more complex in other languages such as German or French, where articles must match the gender and context of a noun.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code><strong>ChoiceFormat<\/strong><\/code>&nbsp;was designed to let you solve this problem. You must specify:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>An array of&nbsp;<em>limits<\/em><\/li><li>An array of&nbsp;<em>format strings<\/em><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of how to solve the above problem:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.ChoiceFormat;\nimport java.text.MessageFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        double&#x5B;] limits = {1, 1, 2};\n        String&#x5B;] formatStrings = \n\t\t{&quot;no houses&quot;, &quot;one house&quot;, \n                    &quot;{1,number,integer} houses&quot;};\n        ChoiceFormat choiceFormat = \n\t\t\tnew ChoiceFormat(limits, formatStrings);\n        String pattern = \n         &quot;On {2,date,long}, {0} &quot; +\n         &quot;destroyed {1}, and caused {3,number,currency} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        msgFormat.setFormat(2, choiceFormat);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;an earthquake&quot;, \n            new Integer(1), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which outputs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>On January 1, 1999, an earthquake destroyed one house, and caused $100,000,000.00 of damage.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Or, we can embed the same choices into the placeholders themselves:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.text.MessageFormat;\nimport java.util.GregorianCalendar;\n\npublic class FormatText\n{\n    public static void main(String&#x5B;] args)\n    {\n        String pattern = \n         &quot;On {2,date,long}, {0} destroyed &quot; +\n         &quot;{1,choice,0#no houses|1#one house|2#{1,number,integer} houses}, &quot; +\n         &quot;and caused {3,number,currency} of damage.&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Object&#x5B;] msgArgs =\n        { \n            &quot;an earthquake&quot;, \n            new Integer(1), \n            new GregorianCalendar(1999, 0, 1).getTime(),\n            new Double(10E7)\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This is actually far preferred, because it means that we can remove the message(s) from the program, and provide separate sets of messages for each language\/locale, and have the separated messages contain all the necessary instructions to format the messages correctly in each language.&nbsp; That way, the program does not have special code for each language.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Believe me, this is very important when you are writing code that will have to be internationalized (globalization is here, already!)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Summary_of_Patterns\"><\/span>Summary of Patterns<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Summary_of_MessageFormat_Patterns\"><\/span>Summary of MessageFormat Patterns<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the grammar for&nbsp;<code><strong>MessageFormat<\/strong><\/code>&nbsp;Patterns:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>messageFormatPattern := string ( \"{\" messageFormatElement \"}\" string )* <\/strong><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>messageFormatElement := argument { \",\" elementFormat } <\/strong><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>elementFormat := \"time\" { \",\" datetimeStyle }\n               | \"date\" { \",\" datetimeStyle }\n               | \"number\" { \",\" numberStyle }\n               | \"choice\" { \",\" choiceStyle } <\/strong><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>datetimeStyle := \"short\"\n               | \"medium\"\n               | \"long\"\n               | \"full\"\n               | dateFormatPattern <\/strong><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>numberStyle := \"currency\"\n             | \"percent\"\n             | \"integer\"\n             | numberFormatPattern <\/strong><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>choiceStyle := choiceFormatPattern<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Notes:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>If there is no&nbsp;<code><strong>elementFormat<\/strong><\/code>, then the argument must be a&nbsp;<code><strong>String<\/strong><\/code>, which is substituted.<\/li><li>If there is no&nbsp;<code><strong>dateTimeStyle<\/strong><\/code>&nbsp;or&nbsp;<code><strong>numberStyle<\/strong><\/code>, then the default format is used (for example, <code><strong>NumberFormat.getInstance<\/strong><\/code>, <code><strong>DateFormat.getTimeInstance<\/strong><\/code>, or <code><strong>DateFormat.getInstance<\/strong><\/code>).<\/li><li>In strings, single quotes can be used to quote the &#8220;<strong><code>{<\/code><\/strong>&#8221; (curly brace) if necessary. A real single quote is represented by&nbsp;<code><strong>''&nbsp;<\/strong><\/code>(two successive single quotes). Inside a&nbsp;<code><strong>messageFormatElement<\/strong><\/code>, quotes are&nbsp;<em>not<\/em>&nbsp;removed. For example,&nbsp;<code><strong>{1,number,$'#',##}<\/strong><\/code>&nbsp;will produce a number format with the pound-sign quoted, with a result such as: &#8220;<strong><code>$#31,45<\/code><\/strong>&#8220;.<\/li><li>If a pattern is used, then unquoted braces in the pattern, if any, must match: that is, <strong>&#8220;<code>ab {0} de<\/code>&#8220;<\/strong> and <strong>&#8220;<code>ab '}' de<\/code>&#8220;<\/strong> are OK, but <strong>&#8220;<code>ab {0'}' de<\/code>&#8220;<\/strong> and <strong>&#8220;<code>ab } de<\/code>&#8220;<\/strong> are not.<\/li><li>The argument is a number from&nbsp;<code>0<\/code>&nbsp;to&nbsp;<code>9<\/code>, which corresponds to the arguments presented in an array to be formatted.<\/li><li>It is ok to have unused arguments in the array. With missing arguments or arguments that are not of the right class for the specified format, a&nbsp;<code><strong>ParseException<\/strong><\/code>&nbsp;is thrown. First,&nbsp;<code><strong>format<\/strong><\/code>&nbsp;checks to see if a&nbsp;<code><strong>Format<\/strong><\/code>&nbsp;object has been specified for the argument with the&nbsp;<code><strong>setFormats<\/strong><\/code>&nbsp;method. If so, then&nbsp;<code><strong>format<\/strong><\/code>&nbsp;uses that&nbsp;<strong>Format<\/strong>&nbsp;object to format the argument. Otherwise, the argument is formatted based on the object&#8217;s type:<ul><li>If the argument is a&nbsp;<code><strong>Number<\/strong><\/code>, then format uses <code><strong>NumberFormat.getInstance<\/strong><\/code> to format the argument;&nbsp;<\/li><li>if the argument is a&nbsp;<code><strong>Date<\/strong><\/code>, then format uses <code><strong>DateFormat.getDateTimeInstance<\/strong><\/code> to format the argument.<\/li><li>Otherwise, it uses the&nbsp;<code><strong>toString<\/strong><\/code>&nbsp;method.<\/li><\/ul><\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Summary_of_ChoiceFormat\"><\/span>Summary of ChoiceFormat<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A&nbsp;<code><strong>ChoiceFormat<\/strong><\/code>&nbsp;allows you to attach a format to a range of numbers. It is generally used in a&nbsp;<code><strong>MessageFormat<\/strong><\/code>&nbsp;for handling plurals. The choice is specified with an ascending list of&nbsp;<code><strong>double<\/strong><\/code>s, where each item specifies a half-open interval up to the next item:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>X matches j if and only if limit[j] &lt;= X &lt; limit[j+1] <\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If there is no match, then either the first or last index is used, depending on whether the number (<code>X<\/code>) is too low or too high.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Formatting_Numbers\"><\/span>Formatting Numbers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When you use&nbsp;<code><strong>MessageFormat<\/strong><\/code>&nbsp;and provide a number as one of the arguments, you must specify an object, not a primitive type. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<code><strong>Number<\/strong><\/code>&nbsp;class hierarchy is as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Number<\/strong><ul><li><strong>Byte<\/strong><\/li><li><strong>Double<\/strong><\/li><li><strong>Float<\/strong><\/li><li><strong>Integer<\/strong><\/li><li><strong>Long<\/strong><\/li><li><strong>Short<\/strong><\/li><li><strong>BigInteger<\/strong><\/li><li><strong>BigDecimal<\/strong><\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The family of classes used to format numbers is:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>Format<\/code><ul><li><code><strong>NumberFormat<\/strong><\/code><ul><li><code><strong>DecimalFormat<\/strong><\/code><\/li><li><code>ChoiceFormat<\/code><\/li><\/ul><\/li><\/ul><\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_NumberFormat\"><\/span>Using NumberFormat<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><code><strong>NumberFormat<\/strong><\/code>&nbsp;is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. <code><strong>NumberFormat<\/strong><\/code> also provides methods for determining which locales have number formats, and what their names are. <code><strong>NumberFormat<\/strong><\/code> helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To format a number for the current&nbsp;<code><strong>Locale<\/strong><\/code>, use one of the factory class methods:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>myString = NumberFormat.getInstance().format(myNumber);<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the system doesn&#8217;t have to fetch the information about the local language and country conventions multiple times.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>NumberFormat nf = NumberFormat.getInstance();\nfor (int i = 0; i &lt; a.length; ++i) \n{\n     output.println(nf.format(myNumber[i]) + \"; \");\n}<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To format a number for a different&nbsp;<code><strong>Locale<\/strong><\/code>, specify it in the call to&nbsp;<code><strong>getInstance<\/strong><\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use a&nbsp;<code><strong>NumberFormat<\/strong><\/code>&nbsp;to parse numbers:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>myNumber = nf.parse(myString);<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use&nbsp;<code><strong>getInstance<\/strong><\/code>&nbsp;or&nbsp;<code><strong>getNumberInstance<\/strong><\/code>&nbsp;to get the normal number format. Use&nbsp;<code><strong>getCurrencyInstance<\/strong><\/code>&nbsp;to get the currency number format. And use&nbsp;<code>getPercentInstance<\/code>&nbsp;to get a format for displaying percentages. With this format, a fraction like&nbsp;<strong><code>0.53<\/code><\/strong>&nbsp;is displayed as&nbsp;<strong><code>53%<\/code><\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can also control the display of numbers with such methods as&nbsp;<code><strong>setMinimumFractionDigits<\/strong><\/code>. If you want even more control over the format or parsing, or want to give your users more control, you can try casting the&nbsp;<code><strong>NumberFormat<\/strong><\/code>&nbsp;you get from the factory methods to a&nbsp;<code><strong>DecimalFormat<\/strong><\/code>. This will work for the vast majority of locales; just remember to put it in a&nbsp;<code>try<\/code>&nbsp;block in case you encounter an unusual one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code><strong>NumberFormat<\/strong><\/code>&nbsp;and&nbsp;<code><strong>DecimalFormat<\/strong><\/code>&nbsp;are designed such that some controls work for formatting and others work for parsing. The following is the detailed description for each these control methods,<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code><strong>setParseIntegerOnly<\/strong><\/code>&nbsp;: only affects parsing, e.g. if true, &#8220;<strong><code>3456.78<\/code><\/strong>&#8221; -&gt;&nbsp;<strong><code>3456<\/code><\/strong>&nbsp;(and leaves the parse position just after index&nbsp;<strong><code>6<\/code><\/strong>) if false, &#8220;<strong><code>3456.78<\/code><\/strong>&#8221; -&gt;&nbsp;<strong><code>3456.78<\/code><\/strong>&nbsp;(and leaves the parse position just after index&nbsp;<strong><code>8<\/code><\/strong>) This is independent of formatting. If you want to not show a decimal point where there might be no digits after the decimal point, use&nbsp;<code><strong>setDecimalSeparatorAlwaysShown<\/strong><\/code>.<\/li><li><code><strong>setDecimalSeparatorAlwaysShown<\/strong><\/code>&nbsp;: only affects formatting, and only where there might be no digits after the decimal point, such as with a pattern like &#8220;<strong><code>#,##0.##<\/code><\/strong>&#8220;, e.g., if true,&nbsp;<strong><code>3456.00<\/code><\/strong>&nbsp;-&gt; &#8220;<strong><code>3,456.<\/code><\/strong>&#8221; if false,&nbsp;<strong><code>3456.00<\/code><\/strong>&nbsp;-&gt; &#8220;<strong><code>3456<\/code><\/strong>&#8221; This is independent of parsing. If you want parsing to stop at the decimal point, use&nbsp;<code><strong>setParseIntegerOnly<\/strong><\/code>.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use forms of the&nbsp;<code>parse<\/code>&nbsp;and&nbsp;<code>format<\/code>&nbsp;methods with&nbsp;<code><strong>ParsePosition<\/strong><\/code>&nbsp;and&nbsp;<code><strong>FieldPosition<\/strong><\/code>&nbsp;to allow you to:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>progressively parse through pieces of a string<\/li><li>align the decimal point and other areas For example, you can align numbers in two ways:<ol><li>If you are using a monospaced font with spacing for alignment, you can pass the&nbsp;<code><strong>FieldPosition<\/strong><\/code>&nbsp;in your&nbsp;<code><strong>format<\/strong><\/code>&nbsp;call, with&nbsp;<code><strong>field = INTEGER_FIELD<\/strong><\/code>. On output,&nbsp;<code><strong>getEndIndex<\/strong><\/code>&nbsp;will be set to the offset between the last character of the integer and the decimal. Add <strong>(<code>desiredSpaceCount - getEndIndex<\/code>)<\/strong> spaces at the front of the string.<\/li><li>If you are using proportional fonts, instead of padding with spaces, measure the width of the string in pixels from the start to&nbsp;<code><strong>getEndIndex<\/strong><\/code>. Then move the pen by <strong>(<code>desiredPixelWidth - widthToAlignmentPoint<\/code>)<\/strong> before drawing the text. It also works where there is no decimal, but possibly additional characters at the end, e.g. with parentheses in negative numbers: &#8220;<strong><code>(12)<\/code><\/strong>&#8221; for&nbsp;<strong><code>-12<\/code><\/strong>.<\/li><\/ol><\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_DecimalFormat\"><\/span>Using DecimalFormat<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><code><strong>DecimalFormat<\/strong><\/code>&nbsp;is a concrete subclass of&nbsp;<code><strong>NumberFormat<\/strong><\/code>&nbsp;for formatting decimal numbers. This class allows for a variety of parameters, and localization to Western, Arabic, or Indic numbers. Normally, you get the proper&nbsp;<code><strong>NumberFormat<\/strong><\/code>&nbsp;for a specific locale (including the default locale) using one of&nbsp;<code><strong>NumberFormat<\/strong><\/code>&#8216;s factory methods such as&nbsp;<code>getInstance<\/code>. You may then modify it from there (after testing to make sure it is a <code><strong>DecimalFormat<\/strong><\/code>, of course!)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Special cases<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>NaN<\/strong>&nbsp;(IEEE floating point &#8220;not-a-number&#8221;) is formatted as a single character, typically&nbsp;<strong><code>\\uFFFD<\/code><\/strong>.<\/li><li><strong>+\/- Infinity<\/strong>&nbsp;is formatted as a single character, typically&nbsp;<strong><code>\\u221E<\/code><\/strong>, plus the positive and negative pre\/suffixes.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> this class is designed for common users; for very large or small numbers, use a format that can express exponential values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The following shows the structure of the pattern:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>pattern    := subpattern{;subpattern}\n \nsubpattern := {prefix}integer{.fraction}{suffix}\n \nprefix     := '\\\\u0000'..'\\\\uFFFD' - specialCharacters\nsuffix     := '\\\\u0000'..'\\\\uFFFD' - specialCharacters\ninteger    := '#'* '0'* '0'\nfraction   := '0'* '#'* \n<\/strong>\nNotation:\n  X*       0 or more instances of X\n  (X | Y)  either X or Y.\n  X..Y     any character from X up to Y, inclusive.\n  S - T    characters in S, except those in T  <\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first subpattern is for positive numbers. The second (optional) subpattern is for negative numbers. (In both cases, &#8216;<strong>,<\/strong>&#8216; can occur inside the integer portion &#8212; it is just too messy to indicate in BNF &#8212; <em>Backus\u2013Naur form<\/em>, used above.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the special characters used in the parts of the subpattern:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th>Symbol<\/th><th>Meaning<\/th><\/tr><tr><td><strong>0<\/strong><\/td><td>a digit<\/td><\/tr><tr><td><strong>#<\/strong><\/td><td>a digit, zero shows as absent<\/td><\/tr><tr><td><strong>.<\/strong><\/td><td>placeholder for decimal separator<\/td><\/tr><tr><td><strong>,<\/strong><\/td><td>placeholder for grouping separator.<\/td><\/tr><tr><td><strong>;<\/strong><\/td><td>separates formats.<\/td><\/tr><tr><td><strong>&#8211;<\/strong><\/td><td>default negative prefix.<\/td><\/tr><tr><td><strong>%<\/strong><\/td><td>multiply by 100 and show as percentage<\/td><\/tr><tr><td><strong>\u2030<\/strong><\/td><td>multiply by 1000 and show as per mille<\/td><\/tr><tr><td><strong>\u00a4<\/strong><\/td><td>currency sign; replaced by currency symbol; if doubled, replaced by international currency symbol. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.<\/td><\/tr><tr><td><strong>X<\/strong><\/td><td>any other characters can be used in the prefix or suffix<\/td><\/tr><tr><td><strong>&#8216;<\/strong><\/td><td>used to quote special characters in a prefix or suffix.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some examples of typical format string usage:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><th><strong>Format String<\/strong><\/th><th><strong>Meaning<\/strong><\/th><th><strong>Value<\/strong><\/th><th><strong>Output String<\/strong><\/th><\/tr><tr><td><strong>&#8220;##0.00&#8221;<\/strong><\/td><td>At least one digit before the decimal point, and two after.<\/td><td><code>1234.567<br>.256<\/code><\/td><td><code>1234.56<br>0.25<\/code><\/td><\/tr><tr><td><strong>&#8220;#.000&#8221;<\/strong><\/td><td>Possibly no digits before the point, three after.<\/td><td><code>1234.567<br>.256<\/code><\/td><td><code>1234.567<br>.256<\/code><\/td><\/tr><tr><td><strong>&#8220;,###&#8221;<\/strong><\/td><td>Use thousands separator and no decimal places.<\/td><td><code>1234.567<br>.256<\/code><\/td><td><code>1,234<br>0<\/code><\/td><\/tr><tr><td><strong>&#8220;0.00;0.00-&#8220;<\/strong><\/td><td>Show negative numbers with sign on the right.<\/td><td><code>-27.5<\/code><\/td><td><code>27.5-<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Notes<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>If there is no explicit negative subpattern, &#8211; is prefixed to the positive form. That is, &#8220;<strong><code>0.00<\/code><\/strong>&#8221; alone is equivalent to &#8220;<strong><code>0.00;-0.00<\/code><\/strong>&#8220;.<\/li><li>Illegal patterns, such as &#8220;<code><strong>#.#.#<\/strong><\/code>&#8221; or mixing &#8216;<strong><code>_<\/code><\/strong>&#8216; and &#8216;<strong><code>*<\/code><\/strong>&#8216; in the same pattern, will cause an&nbsp;<code><strong>IllegalArgumentException<\/strong><\/code>&nbsp;to be thrown. From the message of&nbsp;<code><strong>IllegalArgumentException<\/strong><\/code>, you can find the place in the string where the error occurred.<\/li><li>The grouping separator is commonly used for thousands, but in some countries for ten-thousands. The interval is a constant number of digits between the grouping characters, such as <strong><code>100,000,000<\/code><\/strong> or <strong><code>1,0000,0000<\/code><\/strong>. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So &#8220;<strong><code>#,##,###,####<\/code><\/strong>&#8221; == &#8220;<strong><code>######,####<\/code><\/strong>&#8221; == &#8220;<strong><code>##,####,####<\/code><\/strong>&#8220;.<\/li><li>When calling&nbsp;<code><strong>DecimalFormat.parse(String, ParsePosition)<\/strong><\/code>&nbsp;and parsing fails, a <strong>null<\/strong> object will be returned. The unchanged parse position also reflects that an error has occurred during parsing. When calling the convenient method&nbsp;<code><strong>DecimalFormat.parse(String)<\/strong><\/code>&nbsp;and parsing fails, a&nbsp;<code><strong>ParseException<\/strong><\/code>&nbsp;will be thrown.<\/li><li>This class only handles localized digits where the 10 digits are contiguous in Unicode, from 0 to 9. Other digits sets (such as superscripts) would need a different subclass.<\/li><\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"DecimalFormat_Example\"><\/span>DecimalFormat Example<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example using&nbsp;<strong><code>DecimalFormat<\/code><\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n \n import java.util.Locale;\n import java.text.DecimalFormat;\n import java.text.NumberFormat;\n import java.text.ParseException;\n \n public class FormatDecimal\n {\n    public static void main(String&#x5B;] args)\n    {\n        \/\/ Gather the available locales\n        Locale&#x5B;] locales = NumberFormat.getAvailableLocales();\n\n        double myNumber = -1234.56;\n        NumberFormat form;\n\n        \/\/ Print out a number with the locale number, currency\n        \/\/ and percent format for each locale we can.\n        for (int j = 0; j &lt; 3; ++j) \n        {\n            System.out.println(&quot;FORMAT&quot;);\n            for (int i = 0; i &lt; locales.length; ++i) \n            {\n                if (locales&#x5B;i].getCountry().length() == 0) \n                {\n                    \/\/ skip language-only\n                    continue;\n                }\n                System.out.print(locales&#x5B;i].getDisplayName());\n                switch (j) \n                {\n                  default:\n                    form = NumberFormat.getInstance(locales&#x5B;i]); \n                    break;\n                  case 1:\n                    form = NumberFormat.getCurrencyInstance(locales&#x5B;i]); \n                    break;\n                  case 0:\n                    form = NumberFormat.getPercentInstance(locales&#x5B;i]); \n                    break;\n                }\n                try \n                {\n                    System.out.print(&quot;: &quot; + \n                                     ((DecimalFormat)form).toPattern() +\n                                     &quot; -&gt; &quot; + form.format(myNumber));\n                } \n                catch (IllegalArgumentException iae) \n                { }\n                try \n                {\n                    System.out.println(&quot; -&gt; &quot; + \n                                       form.parse(\n                                            form.format(myNumber)));\n                } \n                catch (ParseException pe) \n                { }\n            }\n        }\n    }\n }\n\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which, on my Microsoft Windows system, prints out a very long list:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>FORMAT\nArabic (Egypt): #,##0% -&gt; -123,456% -&gt; -1234.56\nByelorussian (Belarus): #,##0% -&gt; -123&nbsp;456% -&gt; -1234.56\nBulgarian (Bulgaria): #,##0% -&gt; -123&nbsp;456% -&gt; -1234.56\nCatalan (Spain): #,##0% -&gt; -123.456% -&gt; -1234.56\nCzech (Czech Republic): #,##0% -&gt; -123.456% -&gt; -1234.56\nDanish (Denmark): #,##0% -&gt; -123.456% -&gt; -1234.56\nGerman (Germany): #,##0% -&gt; -123.456% -&gt; -1234.56\nGerman (Germany,Euro): #,##0% -&gt; -123.456% -&gt; -1234.56\nGerman (Austria): #,##0% -&gt; -123.456% -&gt; -1234.56\nGerman (Austria,Euro): #,##0% -&gt; -123.456% -&gt; -1234.56\nGerman (Switzerland): #,##0% -&gt; -123'456% -&gt; -1234.56\nGerman (Luxembourg): #,##0% -&gt; -123.456% -&gt; -1234.56\nGerman (Luxembourg,Euro): #,##0% -&gt; -123.456% -&gt; -1234.56\nGreek (Greece): #,##0% -&gt; -123.456% -&gt; -1234.56\nEnglish (United States): #,##0% -&gt; -123,456% -&gt; -1234.56\nEnglish (Australia): #,##0% -&gt; -123,456% -&gt; -1234.56\nEnglish (Canada): #,##0% -&gt; -123,456% -&gt; -1234.56\nEnglish (United Kingdom): #,##0% -&gt; -123,456% -&gt; -1234.56\nEnglish (Ireland): #,##0% -&gt; -123,456% -&gt; -1234.56\n...\nJapanese (Japan): #,##0.### -&gt; -1,234.56 -&gt; -1234.56\nKorean (South Korea): #,##0.### -&gt; -1,234.56 -&gt; -1234.56\nLithuanian (Lithuania): #,##0.## -&gt; -1.234,56 -&gt; -1234.56\nLatvian (Lettish) (Latvia): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nMacedonian (Macedonia): #,##0.###;(#,##0.###) -&gt; (1.234,56) -&gt; -1234.56\nDutch (Netherlands): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nDutch (Netherlands,Euro): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nDutch (Belgium): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nDutch (Belgium,Euro): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nNorwegian (Norway,B): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nNorwegian (Norway,NY): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nPolish (Poland): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nPortuguese (Portugal): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nPortuguese (Portugal,Euro): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nPortuguese (Brazil): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nRomanian (Romania): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nRussian (Russian Federation): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nSerbo-Croatian (Yugoslavia): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nSlovak (Slovakia): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nSlovenian (Slovenia): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nAlbanian (Albania): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nSerbian (Yugoslavia): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nSwedish (Sweden): #,##0.### -&gt; -1&nbsp;234,56 -&gt; -1234.56\nThai (Thailand): #,##0.### -&gt; -1,234.56 -&gt; -1234.56\nTurkish (Turkey): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nUkrainian (Ukraine): #,##0.### -&gt; -1.234,56 -&gt; -1234.56\nChinese (China): #,##0.### -&gt; -1,234.56 -&gt; -1234.56\nChinese (Taiwan): #,##0.### -&gt; -1,234.56 -&gt; -1234.56\n<\/strong><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_MessageFormat\"><\/span>Using MessageFormat<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">However, for most purposes, you can use&nbsp;<code><strong>MessageFormat<\/strong><\/code>&nbsp;to format numbers:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n \n import java.text.MessageFormat;\n \n public class FormatNumber\n {\n    public static void main(String&#x5B;] args)\n    {\n        Customer&#x5B;] cust = \n        {\n            new Customer(1, &quot;Heather Gilmartin&quot;, 200.00),\n            new Customer(2, &quot;Bill Gates&quot;, -3000000.00),\n            new Customer(500, &quot;Crocodile Dundee&quot;, 1000.00)\n        };\n        for (int i = 0; i &lt; cust.length; i++)\n        {\n            printCustomerStatus(cust&#x5B;i]);\n        }\n    }\n    \n    static void printCustomerStatus(Customer cust)\n    {\n        String pattern = \n            &quot;Customer {0,number,000}, {1}, has a balance of &quot; +\n            &quot;{2,number,\u00a4###,##0.00;(\u00a4###,##0.00)}&quot;; \/\/}&quot;;\n        MessageFormat msgFormat = new MessageFormat(pattern);\n        Object&#x5B;] msgArgs = \n        {\n            new Integer(cust.getId()),\n            cust.getName(),\n            new Double(cust.getBalance())\n        };\n        System.out.println(msgFormat.format(msgArgs));\n    }\n    \n    static class Customer\n    {\n        Customer(int id, String name, double balance)\n        {\n            m_id = id;\n            m_name = name;\n            m_balance = balance;\n        }\n        \n        int     getId()     { return m_id; }\n        String  getName()   { return m_name; }\n        double  getBalance(){ return m_balance; }\n        \n        private int     m_id;\n        private String  m_name;\n        private double  m_balance;\n    }\n }\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Customer 001, Heather Gilmartin, has a balance of $200.00\nCustomer 002, Bill Gates, has a balance of ($3,000,000.00)\nCustomer 500, Crocodile Dundee, has a balance of $1,000.00<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_printf_Family\"><\/span>The printf Family<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In Java 5, they finally added a&nbsp;<strong><code>printf<\/code><\/strong>&nbsp;functionality similar to that of C\/C++ and other languages.&nbsp; It was difficult to do that before Java 5 because there was no support for <em>variable-length argument lists<\/em> &#8212; they added support for that in Java 5.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, here&#8217;s how&nbsp;<strong>printf&nbsp;<\/strong>and family work&#8230;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Classes_Involved\"><\/span>Classes Involved<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the players in this new&nbsp;<strong>printf<\/strong>&nbsp;game:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>The class <strong>java.io.<code>PrintStream<\/code><\/strong> has added new methods:<\/td><td>public PrintStream <strong>printf<\/strong>(String&nbsp;format, Object&#8230;&nbsp;args)public PrintStream <strong>printf<\/strong>(Locale&nbsp;l, String&nbsp;format, Object&#8230;&nbsp;args)public PrintStream <strong>format<\/strong>(String&nbsp;format, Object&#8230;&nbsp;args)public PrintStream <strong>format<\/strong>(Locale&nbsp;l, String&nbsp;format, Object&#8230;&nbsp;args)<\/td><\/tr><tr><td>The class <strong>java.io.<\/strong><code><strong>PrintWriter<\/strong><\/code> has added new methods:<\/td><td>public PrintWriter <strong>printf<\/strong>(String&nbsp;format, Object&#8230;&nbsp;args)public PrintWriter <strong>printf<\/strong>(Locale&nbsp;l, String&nbsp;format, Object&#8230;&nbsp;args)public PrintWriter <strong>format<\/strong>(String&nbsp;format, Object&#8230;&nbsp;args)public PrintWriter <strong>format<\/strong>(Locale&nbsp;l, String&nbsp;format, Object&#8230;&nbsp;args)<\/td><\/tr><tr><td>The class <strong>java.lang.<code>String<\/code><\/strong> has added new methods:<\/td><td>public static String <strong>format<\/strong>(String&nbsp;format, Object&#8230;&nbsp;args)public static String <strong>format<\/strong>(Locale&nbsp;l, String&nbsp;format, Object&#8230;&nbsp;args)<\/td><\/tr><tr><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The work is actually performed by class&nbsp;<strong>java.util.Formatter<\/strong>, which is documented (for Java 5.0)&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/docs.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/Formatter.html\" target=\"_blank\">here<\/a>. Almost the entire javadoc for class <strong>Formatter<\/strong> is the specification for how such formatting is supposed to work, so it&#8217;s worth a close read.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Notice that each of the above methods employs the new (as of Java 5\/1.5) variable number of arguments syntax.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In each of the above methods, the parameter,&nbsp;<strong>format<\/strong>, is known as a&nbsp;<em>Format String<\/em>, which may contain zero or more&nbsp;<em>Format Specifiers<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What&#8217;s a Format Specifier?&nbsp; Read on&#8230;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Format_Specifiers\"><\/span>Format Specifiers<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">What&#8217;s a&nbsp;<em>Format Specifier<\/em>?&nbsp; Here&#8217;s the scoop:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A call to one of the methods in the&nbsp;<strong>printf<\/strong>&nbsp;family involves passing in a Format String, which contains:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Normal text<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">plus<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Zero or more Format Specifiers<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In most cases, a Format Specifier is associated with one of the arguments passed in after the Format String argument.&nbsp; A Format Specifier, as its name suggests, specifies the output format for how that argument&#8217;s value should be displayed.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"General_Character_and_Numeric_Type_Format_Specifiers\"><\/span>General, Character and Numeric Type Format Specifiers<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The format specifiers for general, character, and numeric types have the following syntax:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>%[<em>argument_index<\/em>$][<em>flags<\/em>][<em>width<\/em>][.<em>precision<\/em>]<em>conversion<\/em><\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The optional&nbsp;<em><strong>argument_index<\/strong><\/em>&nbsp;is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by &#8220;1$&#8221;, the second by &#8220;2$&#8221;, etc.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The optional&nbsp;<em><strong>flags<\/strong><\/em>&nbsp;is a set of characters that modify the output format. The set of valid flags depends on the conversion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The optional&nbsp;<em><strong>width<\/strong><\/em>&nbsp;is a non-negative decimal integer indicating the minimum number of characters to be written to the output.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The optional&nbsp;<em><strong>precision<\/strong><\/em>&nbsp;is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The required&nbsp;<em><strong>conversion<\/strong><\/em>&nbsp;is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument&#8217;s data type.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Date_and_Time_Format_Specifiers\"><\/span>Date and Time Format Specifiers<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The format specifiers for types which are used to represents dates and times have the following syntax:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>%[<em>argument_index<\/em>$][<em>flags<\/em>][<em>width<\/em>]<em>conversion<\/em><\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The optional&nbsp;<em><strong>argument_index<\/strong><\/em>,&nbsp;<em><strong>flags<\/strong><\/em>&nbsp;and&nbsp;<em><strong>width<\/strong><\/em>&nbsp;are defined as above.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The required&nbsp;<em><strong>conversion<\/strong><\/em>&nbsp;is a two character sequence. The first character is&nbsp;&#8216;t&#8217;&nbsp;or&nbsp;&#8216;T&#8217;. The second character indicates the format to be used. These characters are similar to but not completely identical to those defined by GNU&nbsp;date&nbsp;and POSIX&nbsp;strftime(3c).<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Non-Argument_Format_Specifiers\"><\/span>Non-Argument Format Specifiers<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The format specifiers which do not correspond to arguments have the following syntax:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>%[<em>flags<\/em>][<em>width<\/em>]<em>conversion<\/em><\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The optional&nbsp;<em><strong>flags<\/strong><\/em>&nbsp;and&nbsp;<em><strong>width<\/strong><\/em>&nbsp;is defined as above.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The required&nbsp;<em><strong>conversion<\/strong><\/em>&nbsp;is a character indicating content to be inserted in the output.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Some_Examples\"><\/span>Some Examples<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some examples of how to use&nbsp;<strong>printf<\/strong>&nbsp;and family.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We start out simple, and build up&#8230;<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Plain_print_println\"><\/span>Using Plain print &amp; println<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s take a look at what we get if we just use <strong>System.out.print[ln]<\/strong> calls.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, let&#8217;s produce a table from some employee data.&nbsp;&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Our first attempt will be pretty crude:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code smaller-font\"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\n\/**\n * Class to produce a table of information about customers\n *\/\npublic class EmployeeTablePrinter1\n{\n  public static void main(String&#x5B;] args)\n  {\n    List&lt;Employee1&gt; employees = new ArrayList&lt;Employee1&gt;();\n    \n    \/\/ Populate list with Employees\n    employees.add( new Employee1(1, &quot;Bloggs, Fred&quot;, &quot;10 Firebird Crescent&quot;, \n                                new Date(1976 - 1900, 5 - 1, 20), 40000.00 ) );\n    employees.add( new Employee1(2, &quot;Charles, Cheryl&quot;, &quot;5 Lattice Lane&quot;,\n                                new Date(1989 - 1900, 4 - 1, 3), 50000.00 ) );\n    employees.add( new Employee1(3, &quot;Romney, Titus&quot;, &quot;42 St. Martins Rd.&quot;,\n                                new Date(1973 - 1900, 11 - 1, 19), 45000.00 ) );\n    employees.add( new Employee1(4, &quot;Clinton, Burton&quot;, &quot;567 Nebula Circle&quot;,\n                                new Date(1964 - 1900, 1 - 1, 29), 100000.00 ) );\n    employees.add( new Employee1(5, &quot;McDuff, Hazel&quot;, &quot;1 Church Row&quot;,\n                                new Date(1985 - 1900, 3 - 1, 6), 55000.00 ) );\n    employees.add( new Employee1(6, &quot;Frazier, Bill&quot;, &quot;92 S. Main St.&quot;,\n                                new Date(1980 - 1900, 12 - 1, 5), 70000.00 ) );\n    employees.add( new Employee1(7, &quot;Zambroski, Heather&quot;, &quot;589 Trumpington Place&quot;,\n                                new Date(1959 - 1900, 4 - 1, 3), 50000.00 ) );\n    \n    \/\/ Print out the table of employees\n    Employee1.printHeader();\n    for (Employee1 emp : employees)\n    {\n      emp.print();\n    }\n  }\n}\n\n\/**\n * Class to represent an employee\n *\/\nclass Employee1\n{\n  Employee1(int id, String name, String address, Date dob, double salary)\n  {\n    m_id = id;\n    m_name = name;\n    m_address = address;\n    m_dob = dob;\n    m_salary = salary;\n  }\n  \n  static void printHeader()\n  {\n    System.out.print(&quot;|&quot;);\n    System.out.print(&quot;ID&quot; + &quot;|&quot;);\n    System.out.print(&quot;Name&quot; + &quot;|&quot;);\n    System.out.print(&quot;Address&quot; + &quot;|&quot;);\n    System.out.print(&quot;Date of Birth&quot; + &quot;|&quot;);\n    System.out.println(&quot;Salary&quot; + &quot;|&quot;);  }\n  \n  void print()\n  {\n    System.out.print(&quot;|&quot;);\n    System.out.print(m_id + &quot;|&quot;);\n    System.out.print(m_name + &quot;|&quot;);\n    System.out.print(m_address + &quot;|&quot;);\n    System.out.print(m_dob + &quot;|&quot;);\n    System.out.println(m_salary + &quot;|&quot;);\n  }\n  \n  private int     m_id;\n  private String  m_name;\n  private String  m_address;\n  private Date    m_dob;\n  private double  m_salary;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Notes:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>I have used the&nbsp;<strong>Date<\/strong>&nbsp;class.&nbsp; The particular constructor for&nbsp;<strong>Date<\/strong>&nbsp;that I used is officially deprecated.&nbsp; However, I am using it because it is the simplest form to use for this example (<strong>Calendar<\/strong>, and <strong>GregorianCalendar<\/strong> are far too complex!)<\/li><li>Other annoyances with the&nbsp;<strong>Date<\/strong>&nbsp;class include:<ul><li>The year must be specified from a base of 1900<\/li><li>The month number is zero-based<\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">When run, this program produces the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>|ID|Name|Address|Date of Birth|Salary|\n|1|Bloggs, Fred|10 Firebird Crescent|Thu May 20 00:00:00 EDT 1976|40000.0|\n|2|Charles, Cheryl|5 Lattice Lane|Mon Apr 03 00:00:00 EDT 1989|50000.0|\n|3|Romney, Titus|42 St. Martins Rd.|Mon Nov 19 00:00:00 EST 1973|45000.0|\n|4|Clinton, Burton|567 Nebula Circle|Wed Jan 29 00:00:00 EST 1964|100000.0|\n|5|McDuff, Hazel|1 Church Row|Wed Mar 06 00:00:00 EST 1985|55000.0|\n|6|Frazier, Bill|92 S. Main St.|Fri Dec 05 00:00:00 EST 1980|70000.0|\n|7|Zambroski, Heather|589 Trumpington Place|Fri Apr 03 00:00:00 EST 1959|50000.0|<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Not exactly the best format one could hope for, right?<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Fixing_Some_Problems\"><\/span>Fixing Some Problems<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">What are the problems?&nbsp; Well, here are some:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The most obvious is that the lines that are intended to separate the data items don&#8217;t line up.<\/li><li>The default formatting of the date of birth is likely to be gobbledygook to most people.&nbsp; Besides, we don&#8217;t want the time of birth in there!<\/li><li>Conventionally, monetary amounts, like salary, are presented with a fixed, two digit, size for cents (the fractional part).&nbsp; Also, wouldn&#8217;t we like to know about monetary units?&nbsp; Is the value in dollars or euros or pounds, or what?&nbsp; And wouldn&#8217;t it be nicer to use commas, so we can read it more easily ($40,000.00, for example)?<\/li><li>Perhaps we would expect an ID number to include some number of leading zeros &#8212; say, 0001, instead of simply 1.&nbsp; It&#8217;s conventional to make an ID be of fixed size by inserting those leading zeros.<\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s see if we can fix the last three of these, by switching to using some&nbsp;<strong>printf<\/strong>&nbsp;features:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code smaller-font\"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\n\/**\n * Class to produce a table of information about customers\n *\/\npublic class EmployeeTablePrinter2\n{\n  public static void main(String&#x5B;] args)\n  {\n    List&lt;Employee2&gt; employees = new ArrayList&lt;Employee2&gt;();\n    \n    \/\/ Populate list with Employees\n    employees.add( new Employee2(1, &quot;Bloggs, Fred&quot;, &quot;10 Firebird Crescent&quot;, \n                                new Date(1976 - 1900, 5 - 1, 20), 40000.00 ) );\n    employees.add( new Employee2(2, &quot;Charles, Cheryl&quot;, &quot;5 Lattice Lane&quot;,\n                                new Date(1989 - 1900, 4 - 1, 3), 50000.00 ) );\n    employees.add( new Employee2(3, &quot;Romney, Titus&quot;, &quot;42 St. Martins Rd.&quot;,\n                                new Date(1973 - 1900, 11 - 1, 19), 45000.00 ) );\n    employees.add( new Employee2(4, &quot;Clinton, Burton&quot;, &quot;567 Nebula Circle&quot;,\n                                new Date(1964 - 1900, 1 - 1, 29), 100000.00 ) );\n    employees.add( new Employee2(5, &quot;McDuff, Hazel&quot;, &quot;1 Church Row&quot;,\n                                new Date(1985 - 1900, 3 - 1, 6), 55000.00 ) );\n    employees.add( new Employee2(6, &quot;Frazier, Bill&quot;, &quot;92 S. Main St.&quot;,\n                                new Date(1980 - 1900, 12 - 1, 5), 70000.00 ) );\n    employees.add( new Employee2(7, &quot;Zambroski, Heather&quot;, &quot;589 Trumpington Place&quot;,\n                                new Date(1959 - 1900, 4 - 1, 3), 50000.00 ) );\n    \n    \/\/ Print out the table of employees\n    Employee2.printHeader();\n    for (Employee2 emp : employees)\n    {\n      emp.print();\n    }\n  }\n}\n\n\/**\n * Class to represent an employee\n *\/\nclass Employee2\n{\n  Employee2(int id, String name, String address, Date dob, double salary)\n  {\n    m_id = id;\n    m_name = name;\n    m_address = address;\n    m_dob = dob;\n    m_salary = salary;\n  }\n  \n  static void printHeader()\n  {\n    System.out.printf(&quot;|ID|Name|Address|Date of Birth|Salary|\\n&quot;);\n  }\n  \n  void print()\n  {\n    System.out.printf(&quot;|%04d|%s|%s|%tF|$%,.2f|\\n&quot;, \n                      m_id, m_name, m_address, m_dob, m_salary);\n  }\n  \n  private int     m_id;\n  private String  m_name;\n  private String  m_address;\n  private Date    m_dob;\n  private double  m_salary;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which now produces the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>|ID|Name|Address|Date of Birth|Salary|\n|0001|Bloggs, Fred|10 Firebird Crescent|1976-05-20|$40,000.00|\n|0002|Charles, Cheryl|5 Lattice Lane|1989-04-03|$50,000.00|\n|0003|Romney, Titus|42 St. Martins Rd.|1973-11-19|$45,000.00|\n|0004|Clinton, Burton|567 Nebula Circle|1964-01-29|$100,000.00|\n|0005|McDuff, Hazel|1 Church Row|1985-03-06|$55,000.00|\n|0006|Frazier, Bill|92 S. Main St.|1980-12-05|$70,000.00|\n|0007|Zambroski, Heather|589 Trumpington Place|1959-04-03|$50,000.00|<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notes:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The <strong>ID<\/strong> values are all now 4 characters wide, with leading zeros<\/li><li>The date format is more readable (I chose ISO date format &#8212;&nbsp;<code><strong>YYYY-MM-DD<\/strong><\/code>&nbsp;&#8212; because US date formatting conventions conflict with those used elsewhere in the world.&nbsp; But you can always change it to your own taste.)<\/li><li>The salary now specifies that it is in dollars, and always shows two decimal places and is comma-separated.<\/li><\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Width_Spacing_Justification\"><\/span>Width, Spacing &amp; Justification<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s finally fix those spacing and alignment problems.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are my final changes:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code smaller-font\"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage inputOutput;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\n\/**\n * Class to produce a table of information about customers\n *\/\npublic class EmployeeTablePrinter3\n{\n  public static void main(String&#x5B;] args)\n  {\n    List&lt;Employee3&gt; employees = new ArrayList&lt;Employee3&gt;();\n    \n    \/\/ Populate list with Employees\n    employees.add( new Employee3(1, &quot;Bloggs, Fred&quot;, &quot;10 Firebird Crescent&quot;, \n                                new Date(1976 - 1900, 5 - 1, 20), 40000.00 ) );\n    employees.add( new Employee3(2, &quot;Charles, Cheryl&quot;, &quot;5 Lattice Lane&quot;,\n                                new Date(1989 - 1900, 4 - 1, 3), 50000.00 ) );\n    employees.add( new Employee3(3, &quot;Romney, Titus&quot;, &quot;42 St. Martins Rd.&quot;,\n                                new Date(1973 - 1900, 11 - 1, 19), 45000.00 ) );\n    employees.add( new Employee3(4, &quot;Clinton, Burton&quot;, &quot;567 Nebula Circle&quot;,\n                                new Date(1964 - 1900, 1 - 1, 29), 100000.00 ) );\n    employees.add( new Employee3(5, &quot;McDuff, Hazel&quot;, &quot;1 Church Row&quot;,\n                                new Date(1985 - 1900, 3 - 1, 6), 55000.00 ) );\n    employees.add( new Employee3(6, &quot;Frazier, Bill&quot;, &quot;92 S. Main St.&quot;,\n                                new Date(1980 - 1900, 12 - 1, 5), 70000.00 ) );\n    employees.add( new Employee3(7, &quot;Zambroski, Heather&quot;, &quot;589 Trumpington Place&quot;,\n                                new Date(1959 - 1900, 4 - 1, 3), 50000.00 ) );\n    \n    \/\/ Print out the table of employees\n    Employee3.printHeader();\n    for (Employee3 emp : employees)\n    {\n      emp.print();\n    }\n  }\n}\n\n\/**\n * Class to represent an employee\n *\/\nclass Employee3\n{\n  Employee3(int id, String name, String address, Date dob, double salary)\n  {\n    m_id = id;\n    m_name = name;\n    m_address = address;\n    m_dob = dob;\n    m_salary = salary;\n  }\n  \n  static void printHeader()\n  {\n    System.out.println(ROW_SEPARATOR);\n    System.out.printf(&quot;| %-4s | %-20s | %-25s | %-14s | %-13s |\\n&quot;,\n                      &quot;ID&quot;, &quot;Name&quot;, &quot;Address&quot;, &quot;Date of Birth&quot;, &quot;Salary&quot;);\n    System.out.println(ROW_SEPARATOR);\n  }\n  \n  void print()\n  {\n    System.out.printf(&quot;| %04d | %-20s | %-25s | %-14tF | $%,12.2f |\\n&quot;, \n                      m_id, m_name, m_address, m_dob, m_salary);\n    System.out.println(ROW_SEPARATOR);\n  }\n  \n  private int     m_id;\n  private String  m_name;\n  private String  m_address;\n  private Date    m_dob;\n  private double  m_salary;\n  \n  static private String ROW_SEPARATOR = \n &quot;+------+----------------------+---------------------------+----------------+---------------+&quot;;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted smaller-font\"><strong>+------+----------------------+---------------------------+----------------+---------------+\n| ID   | Name                 | Address                   | Date of Birth  | Salary        |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0001 | Bloggs, Fred         | 10 Firebird Crescent      | 1976-05-20     | $   40,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0002 | Charles, Cheryl      | 5 Lattice Lane            | 1989-04-03     | $   50,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0003 | Romney, Titus        | 42 St. Martins Rd.        | 1973-11-19     | $   45,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0004 | Clinton, Burton      | 567 Nebula Circle         | 1964-01-29     | $  100,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0005 | McDuff, Hazel        | 1 Church Row              | 1985-03-06     | $   55,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0006 | Frazier, Bill        | 92 S. Main St.            | 1980-12-05     | $   70,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+\n| 0007 | Zambroski, Heather   | 589 Trumpington Place     | 1959-04-03     | $   50,000.00 |\n+------+----------------------+---------------------------+----------------+---------------+<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">While far from ideal, it certainly beats our original, crude attempt!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Notes:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>I added a single space on either side of the data item to prevent it from being forced up against the column separator.<\/li><li>I set minimum widths for the fields, to allow each column to be a standard width, including the header.<\/li><li>I forced left alignment on all the header items, the names, addresses and dates of birth.&nbsp; The default alignment is right aligned, and that is most natural for the salary column, where you want the decimal points to align correctly.&nbsp;&nbsp;<\/li><li>Note however, that right alignment causes a slight problem with the salary format: it causes the dollar sign to be separated from the amount.&nbsp; If you wanted to cause the dollar sign to be right up against the amount, then we could do that, but we&#8217;d have to do two levels of formatting.<\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>If you&#8217;ve used C\/C++ I\/O in the past, it may have occurred to you that C&#8217;s printf is pretty convenient for formatting output.&nbsp; So you may have asked yourself:&nbsp; &#8220;Is there anything like&nbsp;printf&nbsp;in Java?&nbsp; How do I gain greater control of formatting my output?&#8221; Before version 5 (1.5) of Java, it wasn&#8217;t easy.&nbsp; Java provided [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":67,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","ocean_front_end_style_editor":"no","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-136","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/136","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/comments?post=136"}],"version-history":[{"count":14,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/136\/revisions"}],"predecessor-version":[{"id":164,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/136\/revisions\/164"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/67"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/media?parent=136"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}