{"id":74284,"date":"2019-07-10T11:00:28","date_gmt":"2019-07-10T08:00:28","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=74284"},"modified":"2022-07-05T23:11:03","modified_gmt":"2022-07-05T20:11:03","slug":"java-printf-method-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","title":{"rendered":"Printf Java Example (with video)"},"content":{"rendered":"<p>In this post, we feature a comprehensive article about the printf Java method. We will see some examples using the System.out.printf method and examples where the printf method can format a string which contains formatting specifiers.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-1-introduction\">1. Introduction<\/h2>\n<p>The Java <a rel=\"noreferrer noopener\" aria-label=\"PrintStream (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/io\/PrintStream.html#printf-java.util.Locale-java.lang.String-java.lang.Object...-\" target=\"_blank\">PrintStream<\/a> class has provided the <code>printf<\/code> method to write a formatted string to the <code>PrintStream<\/code> object since version 5. Here are the method&#8217;s signatures:<\/p>\n<pre class=\"brush:java\">public PrintStream printf(Locale l, String format, Object... args)\npublic PrintStream printf(String format, Object... args)<\/pre>\n<ul class=\"wp-block-list\">\n<li><code>l<\/code> &#8211; a <a rel=\"noreferrer noopener\" aria-label=\"locale (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Locale.html\" target=\"_blank\">locale<\/a> to apply during formatting<\/li>\n<li><code>format<\/code> &#8211; a format string as described in <a rel=\"noreferrer noopener\" aria-label=\"format string syntax (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Formatter.html#syntax\" target=\"_blank\">format string syntax<\/a><\/li>\n<li><code>args<\/code> &#8211; arguments referenced by the format specifiers in the <code>format<\/code> string<\/li>\n<\/ul>\n<p> You can also check this tutorial in the following video: <\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><a href=\"https:\/\/www.youtube.com\/watch?v=HAGh_7zsCdo\"><img decoding=\"async\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/Printf-Java-Example-1024x576.jpg\" alt=\"\" class=\"wp-image-113799\" width=\"512\" height=\"288\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/Printf-Java-Example-1024x576.jpg 1024w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/Printf-Java-Example-300x169.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/Printf-Java-Example-768x432.jpg 768w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/Printf-Java-Example.jpg 1280w\" sizes=\"(max-width: 512px) 100vw, 512px\" \/><\/a><figcaption>Printf Java Example &#8211; Video<\/figcaption><\/figure>\n<\/div>\n<p>The printf method can format a string which contains formatting specifiers for <code>Integer<\/code>, <code>float<\/code>, <code>Date<\/code>, <code>String<\/code>, etc. The formatting specifiers start with <code>%<\/code> and is followed by four optional arguments and one mandatory <code>conversion<\/code> argument.<\/p>\n<pre class=\"brush:bash\">%[argument_index$][flags][width][.precision]conversion<\/pre>\n<div class=\"wp-block-image\">\n<figure class=\"alignright size-large\"><img decoding=\"async\" width=\"150\" height=\"150\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" alt=\"system.out.printf\" class=\"wp-image-1204\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg 150w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo-70x70.jpg 70w\" sizes=\"(max-width: 150px) 100vw, 150px\" \/><\/figure>\n<\/div>\n<ul class=\"wp-block-list\">\n<li><code>argument_index<\/code> &#8211; it is an optional 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.<\/li>\n<li><code>flags<\/code> &#8211; it is an optional set of characters that modify the output format. The set of valid flags depends on the conversion.<\/li>\n<li><code>width<\/code> &#8211; it is an optional positive decimal integer indicating the minimum number of characters to be written to the output.<\/li>\n<li><code>precision<\/code> &#8211; it is an optional non-negative decimal integer used to restrict the number of characters.<\/li>\n<li><code>conversion<\/code> &#8211; it is a mandatory character indicating how the argument should be formatted.<\/li>\n<\/ul>\n<p>In this example, I will demonstrate how to format a string with these formatting specifiers.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-2-technologies-used\">2. Technologies Used<\/h2>\n<p>The example code in this example was built and run with:<\/p>\n<ul class=\"wp-block-list\">\n<li>Java 11<\/li>\n<li>Maven 3.3<\/li>\n<li>Eclipse<\/li>\n<li>Junit 4.12<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-3-maven-project\">3. Maven Project<\/h2>\n<h3 class=\"wp-block-heading\" id=\"h-3-1-dependencies\">3.1 Dependencies<\/h3>\n<p>I will include <code>Junit<\/code> in the <code>pom.xml<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>pom.xml<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:xml\">&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\"\n\txmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n\txsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\"&gt;\n\t&lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n\t&lt;groupId&gt;java-printf-demo&lt;\/groupId&gt;\n\t&lt;artifactId&gt;java-printf-demo&lt;\/artifactId&gt;\n\t&lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n\t&lt;build&gt;\n\t\t&lt;sourceDirectory&gt;src&lt;\/sourceDirectory&gt;\n\t\t&lt;plugins&gt;\n\t\t\t&lt;plugin&gt;\n\t\t\t\t&lt;artifactId&gt;maven-compiler-plugin&lt;\/artifactId&gt;\n\t\t\t\t&lt;version&gt;3.8.0&lt;\/version&gt;\n\t\t\t\t&lt;configuration&gt;\n\t\t\t\t\t&lt;release&gt;11&lt;\/release&gt;\n\t\t\t\t&lt;\/configuration&gt;\n\t\t\t&lt;\/plugin&gt;\n\t\t&lt;\/plugins&gt;\n\t&lt;\/build&gt;\n\t&lt;dependencies&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;junit&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;junit&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;4.12&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t&lt;\/dependencies&gt;\n&lt;\/project&gt;<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-3-2-printfformatbasetest\">3.2 PrintfFormatBaseTest<\/h3>\n<p>Java <a rel=\"noreferrer noopener\" aria-label=\"Formatter  (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Formatter.html#syntax\" target=\"_blank\">Formatter<\/a> class defines the formatting specifiers. Here are some common conversion specifiers:<\/p>\n<ul class=\"wp-block-list\">\n<li>b(B) &#8211; converts a non-null <code>boolean<\/code> or <code>Boolean<\/code> object base on <code>String.valueOf(arg)<\/code>.<\/li>\n<li>c(C) &#8211; transforms a character based on its Unicode<\/li>\n<li>h &#8211; translates based on the <code>hashcode<\/code> method<\/li>\n<li>d &#8211; converts an integer number<\/li>\n<li>f &#8211; converts a float number<\/li>\n<li>n &#8211; converts to a platform-specific line separator <\/li>\n<li>s(S) &#8211; formats a String<\/li>\n<li>t(T) &#8211; converts to a date and time value<\/li>\n<\/ul>\n<p>The following are some common flag specifiers:<\/p>\n<ul class=\"wp-block-list\">\n<li>-: Left-justified<\/li>\n<li>+: Include a sign for a numeric value<\/li>\n<li>0: Zero-padding for a numeric value<\/li>\n<li>,: locale-specific&nbsp;grouping separators <\/li>\n<\/ul>\n<p>In this example, I will create several constants which embed the format specifiers. I will use Junit <code>@Rule<\/code> to print out the test method&#8217;s name. I will also create several test methods to demonstrate the three kinds of argument indexing:<\/p>\n<ul class=\"wp-block-list\">\n<li>explicit indexing &#8211; specifies the argument with explicit indexing, e.g. <code>1$<\/code><\/li>\n<li>ordinary indexing &#8211; the argument-index is based on the position<\/li>\n<li>relative indexing &#8211; uses the same argument with <code>'&lt;'<\/code><\/li>\n<\/ul>\n<p>In the test methods I use the System.out.printf method.<\/p>\n<p><span style=\"text-decoration: underline\"><em>PrintfFormatBaseTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport java.util.MissingFormatArgumentException;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TestRule;\nimport org.junit.rules.TestWatcher;\nimport org.junit.runner.Description;\n\npublic class PrintfFormatBaseTest {\n\t\n\t@Rule\n\tpublic TestRule echoMethodName = new TestWatcher() {\n\t\tprotected void starting(Description desc) {\n\t\t\tSystem.out.println(\"\\nTestMethodName:\" + desc.getMethodName());\n\t\t}\n\t};\n \n\tprotected static final String BOOLEAN_B = \"%%b - format boolean value: %b, %%B - Boolean value: %B\";\n\tprotected static final String CHAR_C = \"%%c - format char with lower-case value: %c, %%C - with upper-case value: %C.\";\n\tprotected static final String DECIMAL_F = \"%%f - doubleValue is: %f. floatValue is: %f\";\n\tprotected static final String DECIMAL_FLAGS_WIDTH_PRECISION = \"%%-+,10.2f - Format a negative number by left-justified, separating with comma, with a sign, 10 width, and 2 precision: %-+,10.2f\";\n\tprotected static final String DECIMAL_PADDING_BLANK = \"%% 10.3f - Format a decimal with padding empty space: % 10.3f\";\n\tprotected static final String DECIMAL_PADDING_ZERO = \"%%010.3f - Format a decimal with padding zero: %010.3f\";\n\n\tprotected static final String EXPONENTIAL_E = \"%%e - exponential number. Value is: %e.\";\n\n\tprotected static final String HASHCODE_H = \"The string object's hashcode: %h, the interger's hashcode: %h\";\n\tprotected static final String INTEGER_D_BASE10 = \"%%d - byteValue is: %d, shortValue is: %d, intValue is: %d, longValue is: %d.\";\n\n\tprotected static final String INTEGER_O_BASE8 = \"%%o - Octal format. byteValue is: %o, shortValue is: %o, intValue is: %o, longValue is: %o.\";\n\tprotected static final String INTEGER_X_BASE16 = \"%%x - Base 16. byteValue is: %x, shortValue is: %x, intValue is: %x, longValue is: %x.\";\n\tprotected static final String NEW_LINE = \"%n\";\n\n\tprotected byte byteValue = 12;\n\tprotected double doubleValue = 10.123;\n\tprotected float floatValue = 123.45f;\n\tprotected int intValue = 123;\n\tprotected long longValue = 1234567;\n\tprotected short shortValue = 121;\n\n\t@Test\n\tpublic void explicit_indexing_test() {\n\t\tSystem.out.printf(\"explicit two arguments: %1$s, %2$s\", \"Hello\", \"World!\");\t\t \n\t}\n\n\t@Test\n\tpublic void explicit_indexing_test_differentOrder() {\n\t\tSystem.out.printf(\"explicit two arguments: %2$s, %1$s\", \"Hao!\", \"Ni\");\t \n\t}\n\n\t@Test(expected = MissingFormatArgumentException.class)\n\tpublic void ordinary_indexing_test_exception() {\n\t\tSystem.out.printf(\"throw MissingFormatArgumentException: %s, %s\", \"test\");\t \n\t}\n\n\t@Test\n\tpublic void relative_indexing_test() {\n\t\tSystem.out.printf(\"relative arguments - %1$s, %&lt;s, %&lt;s, %2$s, and %&lt;s\", \"Zheng\", \"Mary\");\t \n\t}\n\t\n}<\/pre>\n<p>Execute <code>mvn test -Dtest=PrintfFormatBaseTest<\/code> and capture the output.<\/p>\n<p><span style=\"text-decoration: underline\"><em>PrintfFormatBaseTest results.<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo&gt;mvn test -Dtest=PrintfFormatBaseTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] -----------------&lt; java-printf-demo:java-printf-demo &gt;------------------\n[INFO] Building java-printf-demo 0.0.1-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-printf-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-printf-demo ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 7 source files to C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-printf-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-printf-demo ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 7 source files to C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\target\\test-classes\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-printf-demo ---\n[INFO] Surefire report directory: C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.PrintfFormatBaseTest\n\nTestMethodName:explicit_indexing_test_differentOrder\nexplicit two arguments: Ni, Hao!\nTestMethodName:relative_indexing_test\nrelative arguments - Zheng, Zheng, Zheng, Mary, and Mary\nTestMethodName:explicit_indexing_test\nexplicit two arguments: Hello, World!\nTestMethodName:ordinary_indexing_test_exception\nthrow MissingFormatArgumentException: test, Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.157 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time:  10.262 s\n[INFO] Finished at: 2019-07-07T11:50:17-05:00\n[INFO] ------------------------------------------------------------------------\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo&gt;<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-4-format-a-number\">4. Format a Number<\/h2>\n<h3 class=\"wp-block-heading\" id=\"h-4-1-printf-numbertest\">4.1 Printf_NumberTest<\/h3>\n<p>In this step, I will create Junit tests to format a number in several ways:<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<ul class=\"wp-block-list\">\n<li>Formats a number (base 8, 10, and 16) for different data types: <code>byte<\/code>, <code>short<\/code>, <code>int<\/code>, and <code>long<\/code><\/li>\n<li>Formats a float number in exponential format<\/li>\n<li>Formats a decimal number for different data types: <code>float<\/code> and <code>double<\/code><\/li>\n<li>Formats a decimal number with different padding characters: space and zero<\/li>\n<li>Formats a float number with left-justified (-), sign (+), and comma (,) flag, 2 precision (.2), and width 10 specifiers<\/li>\n<\/ul>\n<p> In the test methods I use the System.out.printf method. <\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_NumberTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport org.junit.Test;\n\npublic class Printf_NumberTest extends PrintfFormatBaseTest {\n\n\n\t@Test\n\tpublic void d_for_integer_base10() {\n\t\tSystem.out.printf(INTEGER_D_BASE10, byteValue, shortValue, intValue, longValue);\n\t}\n\n\t@Test\n\tpublic void e_for_exponential_number() {\n\t\tSystem.out.printf(EXPONENTIAL_E, floatValue);\n\t}\n\n\t@Test\n\tpublic void f_for_decimal() {\n\t\tSystem.out.printf(DECIMAL_F, doubleValue, floatValue);\n\t}\n\n\t@Test\n\tpublic void o_for_integer_base8() {\n\t\tSystem.out.printf(INTEGER_O_BASE8, byteValue, shortValue, intValue, longValue);\n\t}\n\n\t@Test\n\tpublic void padding_space() {\n\t\t\/\/ % 10.3f - Format a decimal with padding empty space: 125.100\n\t\tSystem.out.printf(DECIMAL_PADDING_BLANK, 125.1f);\n\t}\n\n\t@Test\n\tpublic void padding_zero() {\n\t\t\/\/ %010.3f - Format a decimal with padding zero: 000125.100\n\t\tSystem.out.printf(DECIMAL_PADDING_ZERO, 125.1f);\n\t}\n\n\t@Test\n\tpublic void with_all_formatting_flags_width_precision() {\n\t\t\/\/ %-+,10.2f - Format a negative number by left-justified, separating with comma,\n\t\t\/\/ with a sign, 10 width, and 2 precision: -12,345.12\n\t\tSystem.out.printf(DECIMAL_FLAGS_WIDTH_PRECISION, -12345.1234f);\n\t}\n\n\t@Test\n\tpublic void x_for_integer_base16() {\n\t\tSystem.out.printf(INTEGER_X_BASE16, byteValue, shortValue, intValue, longValue);\n\t}\n\n}\n<\/pre>\n<p>Execute <code>mvn test -Dtest=Printf_NumberTest<\/code> and capture the output. <\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_NumberTest results<\/em><\/span><\/p>\n<pre class=\"wp-block-preformatted brush:bash\">C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo&gt;mvn test -Dtest=Printf_NumberTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] -----------------&lt; java-printf-demo:java-printf-demo &gt;------------------\n[INFO] Building java-printf-demo 0.0.1-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-printf-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-printf-demo ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 7 source files to C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-printf-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-printf-demo ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-printf-demo ---\n[INFO] Surefire report directory: C:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.Printf_NumberTest\n\nTestMethodName:d_for_integer_base10\n%d - byteValue is: 12, shortValue is: 121, intValue is: 123, longValue is: 1234567.\nTestMethodName:x_for_integer_base16\n%x - Base 16. byteValue is: c, shortValue is: 79, intValue is: 7b, longValue is: 12d687.\nTestMethodName:o_for_integer_base8\n%o - Octal format. byteValue is: 14, shortValue is: 171, intValue is: 173, longValue is: 4553207.\nTestMethodName:e_for_exponential_number\n%e - exponential number. Value is: 1.234500e+02.\nTestMethodName:f_for_decimal\n%f - doubleValue is: 10.123000. floatValue is: 123.449997\nTestMethodName:with_all_formatting_flags_width_precision\n%-+,10.2f - Format a negative number by left-justified, separating with comma, with a sign, 10 width, and 2 precision: -12,345.12\nTestMethodName:padding_zero\n%010.3f - Format a decimal with padding zero: 000125.100\nTestMethodName:padding_space\n% 10.3f - Format a decimal with padding empty space:    125.100\nTestMethodName:explicit_indexing_test_differentOrder\nexplicit two arguments: Ni, Hao!\nTestMethodName:relative_indexing_test\nrelative arguments - Zheng, Zheng, Zheng, Mary, and Mary\nTestMethodName:explicit_indexing_test\nexplicit two arguments: Hello, World!\nTestMethodName:ordinary_indexing_test_exception\nthrow MissingFormatArgumentException: test, Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.193 sec\n\nResults :\n\nTests run: 12, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time:  8.983 s\n[INFO] Finished at: 2019-07-07T11:52:47-05:00\n[INFO] ------------------------------------------------------------------------\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo&gt;<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-2-numberformattest\">4.2 NumberFormatTest<\/h3>\n<p>Java provides a <a rel=\"noreferrer noopener\" aria-label=\"NumberFormat  (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/text\/NumberFormat.html\" target=\"_blank\">NumberFormat<\/a> class to format a number. In this step, I will create several test methods to format a number. It achieves similar formatting results as the <code>printf<\/code> method with more readable code.<\/p>\n<p><span style=\"text-decoration: underline\"><em>NumberFormatTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.text.NumberFormat;\nimport java.util.Locale;\n\nimport org.junit.Test;\n\npublic class NumberFormatTest {\n\n\tprivate NumberFormat usNumFormat = NumberFormat.getInstance(new Locale(\"en\", \"US\"));;\n\n\t@Test\n\tpublic void formatDecimal() {\t \n\t\tusNumFormat.setMaximumFractionDigits(4);\n\t\tusNumFormat.setMinimumFractionDigits(2);\n\t \n\t\tassertEquals(\"123.4568\",  usNumFormat.format(123.45678));\n\t}\n\n\t@Test\n\tpublic void formatInteger() {\n\t\tassertEquals(\"100\", usNumFormat.format(100l));\n\t}\n\n\t@Test\n\tpublic void formatPercentage() {\n\t\tNumberFormat nf = NumberFormat.getPercentInstance();\n\t \n\t\tassertEquals(\"25%\", nf.format(0.25));\n\t}\n\n}\n<\/pre>\n<p>Execute <code>mvn test -Dtest=NumberFormatTest<\/code> and capture the output.  <\/p>\n<p><span style=\"text-decoration: underline\"><em>NumberFormatTest Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.NumberFormatTest\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.174 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-5-format-a-date\">5. Format a Date<\/h2>\n<h3 class=\"wp-block-heading\" id=\"h-5-1-printf-datetest\">5.1 Printf_DateTest<\/h3>\n<p>Java provides additional specifier suffix after the date\/time conversation specifiers: <code>t<\/code> and <code>T<\/code>. <\/p>\n<p>Here are some common date suffix specifiers:<\/p>\n<ul class=\"wp-block-list\">\n<li><code>m<\/code> &#8211; Month, formatted as two digits with leading zeros as necessary, i.e. 01 &#8211; 12<\/li>\n<li><code>d<\/code> &#8211; Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 &#8211; 31<\/li>\n<li><code>y<\/code> &#8211; Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 &#8211; 99<\/li>\n<li><code>Y<\/code> &#8211; Year, formatted to at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar <\/li>\n<\/ul>\n<p>Here are some common time suffix specifiers:<\/p>\n<ul class=\"wp-block-list\">\n<li><code>H<\/code> &#8211; Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as necessary i.e. 00 &#8211; 23.<\/li>\n<li><code>M<\/code> &#8211; Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 &#8211; 59.<\/li>\n<li><code>S<\/code> &#8211; Seconds within the minute, formatted as two digits with a leading zero as necessary, i.e. 00 &#8211; 60 (&#8220;60&#8221; is a special value required to support leap seconds).<\/li>\n<li><code>r<\/code> &#8211; a 12-hour clock time as&nbsp;<code>\"%tI:%tM:%tS %Tp\"<\/code> <\/li>\n<\/ul>\n<p>In this step, I will create several test methods to format a date with the predefined format specifiers, using again the System.out.printf method. <\/p>\n<ul class=\"wp-block-list\">\n<li>Format a data time with <code>tc<\/code><\/li>\n<li>format a date with <code>tD<\/code><\/li>\n<li>format a ISO8601 date with <code>tF<\/code><\/li>\n<li>Format a 12 hour time with <code>tr<\/code><\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><em>Printf_DateTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport java.util.Date;\n\nimport org.junit.Test;\n\npublic class Printf_DateTest extends PrintfFormatBaseTest  {\n\n\t@Test\n\tpublic void tc_detail_date_time() {\n\t\t\/\/ DateTime: Mon Jul 01 23:09:59 CDT 2019\n\t\tSystem.out.printf(\"DateTime: %1$tc\", new Date());\n\t}\n\t\n\t@Test\n\tpublic void Tc_detail_date_time() {\n\t\t\/\/ DateTime: SUN JUL 07 07:19:32 CDT 2019\n\t\tSystem.out.printf(\"DateTime: %1$Tc\", new Date());\n\t}\n\n\t@Test\n\tpublic void tD_month_day_year() {\n\t\t\/\/ Date: 07\/01\/19\n\t\tSystem.out.printf(\"Date: %1$tD\", new Date());\n\t}\n\n\n\t@Test\n\tpublic void dateTime_format_explicating_indexing() {\n\t\t\/\/ Time: 01-07-2019 22:54:31\n\t\t\/\/ td day of month\n\t\tSystem.out.printf(\"Time: %1$td-%1$tm-%1$tY %1$tH:%1$tM:%1$tS\", new Date());\n\t}\n\n\t@Test\n\tpublic void dateTime_format_explicating_indexing_2() {\n\t\t\/\/ Date: July 01 2019\n\t\t\/\/ tB local-specific full month name\n\t\tSystem.out.printf(\"Date: %1$tB %1$td %1$tY\", new Date());\n\t}\n\n\t@Test\n\tpublic void tF_ISO8601() {\n\t\t\/\/ Date: 2019-07-01\n\t\tSystem.out.printf(\"Date: %1$tF\", new Date());\n\t}\n\n\t@Test\n\tpublic void tR_Hour_Minute() {\n\t\t\/\/ tH:tM\n\t\tSystem.out.printf(\"Date: %1$tR\", new Date());\n\t}\n\n\t@Test\n\tpublic void tr_Hour_Minute_Second_12() {\n\t\t\/\/ Time: 11:07:18 PM\n\t\t\/\/ tH:tM:tS\n\t\tSystem.out.printf(\"Time: %1$tr\", new Date());\n\t}\n\n\t@Test\n\tpublic void tT_Hour_Minute_Second() {\n\t\t\/\/ tH:tM:tS\n\t\tSystem.out.printf(\"Date: %1$tT\", new Date());\n\t}\n}\n<\/pre>\n<p>Execute <code>mvn test -Dtest=Printf_DateTest<\/code> and capture the output.  <\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_DateTest Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Running jcg.zheng.demo.Printf_DateTest\n\nTestMethodName:tr_Hour_Minute_Second_12\nTime: 12:00:29 PM\nTestMethodName:tR_Hour_Minute\nDate: 12:00\nTestMethodName:dateTime_format_explicating_indexing_2\nDate: July 07 2019\nTestMethodName:dateTime_format_explicating_indexing\nTime: 07-07-2019 12:00:29\nTestMethodName:tD_month_day_year\nDate: 07\/07\/19\nTestMethodName:tc_detail_date_time\nDateTime: Sun Jul 07 12:00:29 CDT 2019\nTestMethodName:tT_Hour_Minute_Second\nDate: 12:00:29\nTestMethodName:Tc_detail_date_time\nDateTime: SUN JUL 07 12:00:29 CDT 2019\nTestMethodName:tF_ISO8601\nDate: 2019-07-07\nTestMethodName:explicit_indexing_test_differentOrder\nexplicit two arguments: Ni, Hao!\nTestMethodName:relative_indexing_test\nrelative arguments - Zheng, Zheng, Zheng, Mary, and Mary\nTestMethodName:explicit_indexing_test\nexplicit two arguments: Hello, World!\nTestMethodName:ordinary_indexing_test_exception\nthrow MissingFormatArgumentException: test, Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.364 sec\n\nResults :\n\nTests run: 13, Failures: 0, Errors: 0, Skipped: 0\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-5-2-dateformattest\">5.2 DateFormatTest<\/h3>\n<p>Java provides a <a rel=\"noreferrer noopener\" aria-label=\"SimpleDateFormat  (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/text\/SimpleDateFormat.html\" target=\"_blank\">SimpleDateFormat<\/a> and <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/time\/format\/DateTimeFormatter.html\" target=\"_blank\">DateTimeFormatter<\/a> class to format a date. Both classes have similar format specifiers, but the <code>DateTimeFormatter<\/code> class provides static constants for the common formatting patterns. In this step, I will create two test methods to show how to format a date.<\/p>\n<p><span style=\"text-decoration: underline\"><em>DateFormatTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.GregorianCalendar;\n\nimport org.junit.Test;\n\npublic class DateFormatTest {\n\n\t@Test\n\tpublic void dateTimeFormat() {\n\t\tDateFormat df = new SimpleDateFormat(\"dd-MM-yyyy hh:mm:ss\");\n\n\t\tSystem.out.println(df.format((new GregorianCalendar()).getTime()));\n\t}\n\n\t@Test\n\tpublic void DateTimeFormatter_java8() {\n\t\tDateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;\n\n\t\tLocalDateTime now = LocalDateTime.now();\n\t\tSystem.out.println(\"default format:\" + now);\n\n\t\tString formatDateTime = now.format(formatter);\n\n\t\tSystem.out.println(\"ISO_DATE_TIME format : \" + formatDateTime);\n\t}\n\n}\n<\/pre>\n<p> Execute <code>mvn test -Dtest=DateFormatTest<\/code> and capture the output.  <\/p>\n<p><span style=\"text-decoration: underline\"><em>DateFormatTest Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.DateFormatTest\ndefault format:2019-07-07T12:03:39.023577700\nISO_DATE_TIME format : 2019-07-07T12:03:39.0235777\n07-07-2019 12:03:39\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.242 sec\n\nResults :\n\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-6-format-a-string\">6. Format a String <\/h2>\n<h3 class=\"wp-block-heading\" id=\"h-6-1-printf-stringtest\">6.1 Printf_StringTest<\/h3>\n<p>In this step, I will create several Junit test methods to format a string with several conversion specifiers: %c, %b, %h, %s, and %S.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_StringTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport java.io.UnsupportedEncodingException;\n\nimport org.junit.Test;\n\npublic class Printf_StringTest extends PrintfFormatBaseTest {\n\n\tprivate boolean isFalse = false;\n\tprivate Boolean isTrue = Boolean.TRUE;\n\n\t@Test\n\tpublic void b_for_boolean() throws UnsupportedEncodingException {\n\t\tSystem.out.printf(BOOLEAN_B, isFalse, isTrue);\n\t}\n\t\n\t@Test\n\tpublic void b_for_String_always_True() throws UnsupportedEncodingException {\n\t\tSystem.out.printf(BOOLEAN_B, \"test\", 1);\n\t}\n\n\t@Test\n\tpublic void c_for_character() {\n\t\tSystem.out.printf(CHAR_C, 'm', 'm');\n\t}\n\n\t@Test\n\tpublic void h_for_hashcode() {\n\t\tString s = \"Hello World\";\n\t\tInteger number = Integer.valueOf(100);\n\t\tSystem.out.printf(HASHCODE_H, s, number);\n\n\t}\n\n\t@Test\n\tpublic void n_for_newline() {\n\t\tSystem.out.printf(\"Hello World%n2nd line\");\n\t}\n\n\t@Test\n\tpublic void s_for_string() {\n\t\tString stringVal = \"Hi, Mary!\";\n\t\tSystem.out.printf(\"Left-justified is: %-20s\\n\", stringVal);\n\t\tSystem.out.printf(\"Uppercase, Right-justified is: %20S\\n\", stringVal);\n\t}\n\n\t@Test\n\tpublic void s_for_string_width_too_small() {\n\t\tString stringVal = \"Hi, Mary!\";\n\t\tSystem.out.printf(\"width is smaller: %2S\", stringVal);\n\t}\n\n}\n<\/pre>\n<p> Execute <code>mvn test -Dtest=Printf_StringTest<\/code> and capture the output.  <\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_StringTest Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Running jcg.zheng.demo.Printf_StringTest\n\nTestMethodName:b_for_String_always_True\n%b - format boolean value: true, %B - Boolean value: TRUE\nTestMethodName:s_for_string_width_too_small\nwidth is smaller: HI, MARY!\nTestMethodName:n_for_newline\nHello World\n2nd line\nTestMethodName:h_for_hashcode\nThe string object's hashcode: cc969a84, the interger's hashcode: 64\nTestMethodName:b_for_boolean\n%b - format boolean value: false, %B - Boolean value: TRUE\nTestMethodName:s_for_string\nLeft-justified is: Hi, Mary!\nUppercase, Right-justified is:            HI, MARY!\n\nTestMethodName:c_for_character\n%c - format char with lower-case value: m, %C - with upper-case value: M.\nTestMethodName:explicit_indexing_test_differentOrder\nexplicit two arguments: Ni, Hao!\nTestMethodName:relative_indexing_test\nrelative arguments - Zheng, Zheng, Zheng, Mary, and Mary\nTestMethodName:explicit_indexing_test\nexplicit two arguments: Hello, World!\nTestMethodName:ordinary_indexing_test_exception\nthrow MissingFormatArgumentException: test, Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.211 sec\n\nResults :\n\nTests run: 11, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-6-2-printf-filetest\">6.2 Printf_FileTest<\/h3>\n<p>In this step, I will demonstrate how to write the formatted data to a text file with the <code>printf<\/code> method.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_FileTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.PrintStream;\nimport java.util.Date;\n\nimport org.junit.Test;\n\npublic class Printf_FileTest extends PrintfFormatBaseTest {\n\n\t@Test\n\tpublic void writetoFile() {\n\t\tPrintStream writeToFile;\n\t\ttry {\n\t\t\twriteToFile = new PrintStream(new FileOutputStream(\"Printf_demo.txt\", true));\n\n\t\t\twriteToFile.printf(BOOLEAN_B, false, Boolean.TRUE);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(CHAR_C, 'a', 'a');\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\t\n\t\t\twriteToFile.printf(\"%%-20s - Format string with Left-justified and 20 width is: %-20s\", \"Mary Zheng\");\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(\"%%20S - Format string with Uppercase, Right-justified : %20S\", \"Hello\");\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(DECIMAL_F, doubleValue, floatValue);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(EXPONENTIAL_E, floatValue);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(INTEGER_D_BASE10, byteValue, shortValue, intValue, longValue);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(INTEGER_O_BASE8, byteValue, shortValue, intValue, longValue);\t\t\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(INTEGER_X_BASE16, byteValue, shortValue, intValue, longValue);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(DECIMAL_PADDING_BLANK, 125.1f);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(DECIMAL_PADDING_ZERO, 125.1f);\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(DECIMAL_FLAGS_WIDTH_PRECISION, -12345.1234f);\n\t\t\twriteToFile.printf(NEW_LINE);\n\n\t\t\twriteToFile.printf(\"%%1$tc - Format a DateTime: %1$tc\", new Date());\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t\twriteToFile.printf(\"%%1$tD - Format a Date: %1$tD\", new Date());\n\t\t\twriteToFile.printf(NEW_LINE);\t\t \n\t\t\twriteToFile.printf(\"%%1$tT - Format a Time: %1$tT\", new Date());\n\t\t\twriteToFile.printf(NEW_LINE);\n\t\t \n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n}\n<\/pre>\n<p>Execute <code>mvn test -Dtest=Printf_FileTest<\/code> and capture the content of <code>Printf_demo.txt<\/code>.  <\/p>\n<p><span style=\"text-decoration: underline\"><em>Printf_demo.txt<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">%b - format boolean value: false, %B - Boolean value: TRUE\n%c - format char with lower-case value: a, %C - with upper-case value: A.\n%-20s - Format string with Left-justified and 20 width is: Mary Zheng          \n%20S - Format string with Uppercase, Right-justified :                HELLO\n%f - doubleValue is: 10.123000. floatValue is: 123.449997\n%e - exponential number. Value is: 1.234500e+02.\n%d - byteValue is: 12, shortValue is: 121, intValue is: 123, longValue is: 1234567.\n%o - Octal format. byteValue is: 14, shortValue is: 171, intValue is: 173, longValue is: 4553207.\n%x - Base 16. byteValue is: c, shortValue is: 79, intValue is: 7b, longValue is: 12d687.\n% 10.3f - Format a decimal with padding empty space:    125.100\n%010.3f - Format a decimal with padding zero: 000125.100\n%-+,10.2f - Format a negative number by left-justified, separating with comma, with a sign, 10 width, and 2 precision: -12,345.12\n%1$tc - Format a DateTime: Sun Jul 07 12:06:42 CDT 2019\n%1$tD - Format a Date: 07\/07\/19\n%1$tT - Format a Time: 12:06:42\n<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-7-printf-java-example-summary\">7. Printf Java Example \u2013 Summary<\/h2>\n<p>In this example, I demonstrated how to use the <code>printf<\/code> method to:<\/p>\n<ul class=\"wp-block-list\">\n<li>Format a number<\/li>\n<li>Format a date<\/li>\n<li>Format a string<\/li>\n<li>Write to a file<\/li>\n<\/ul>\n<p>I also compared <code>printf<\/code> to <code>NumberFormat<\/code>, <code>SimpleDateFormat<\/code>, and  <code>DateTimeFormatter<\/code>. It is important for the developers to know the printf format specifiers when using the System.out.printf method.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-8-more-articles\">8. More articles<\/h2>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-tutorial-for-beginners\/\">Java Tutorial for Beginners<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/arraylist-java-example\/\">ArrayList Java Example \u2013 How to use arraylist<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/hashmap-java-example\/\">Hashmap Java Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-array-example\/\">Java Array \u2013 java.util.Arrays Example (with Video)<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-string-class-example\/\">Java String Class Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-list-example\/\">Java List Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-util-scanner-scanner-java-example\/\">java.util.Scanner \u2013 Scanner Java Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-map-example\/\">Java Map Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-queue-example\/\">Java Queue Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-stack-example\/\">Java Stack Example<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-9-download-the-source-code\">9. Download the Source Code<\/h2>\n<p>This was an example on  Java printf() Method . This example consists of a Maven project which defines seven test classes to demonstrate the <code>printf<\/code> method&#8217;s usages.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2019\/07\/java-printf-demo.zip\"><strong>Printf Java Example<\/strong><\/a><\/div>\n<p><strong>Last updated on May 31st, 2021<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we feature a comprehensive article about the printf Java method. We will see some examples using the System.out.printf method and examples where the printf method can format a string which contains formatting specifiers. 1. Introduction The Java PrintStream class has provided the printf method to write a formatted string to the PrintStream &hellip;<\/p>\n","protected":false},"author":140,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-74284","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-core-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Printf Java Example (with video) - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Printf Java Example (with video) - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2019-07-10T08:00:28+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-07-05T20:11:03+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Mary Zheng\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Mary Zheng\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\"},\"author\":{\"name\":\"Mary Zheng\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae\"},\"headline\":\"Printf Java Example (with video)\",\"datePublished\":\"2019-07-10T08:00:28+00:00\",\"dateModified\":\"2022-07-05T20:11:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\"},\"wordCount\":1109,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"articleSection\":[\"Core Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\",\"name\":\"Printf Java Example (with video) - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2019-07-10T08:00:28+00:00\",\"dateModified\":\"2022-07-05T20:11:03+00:00\",\"description\":\"Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Printf Java Example (with video)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae\",\"name\":\"Mary Zheng\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg\",\"caption\":\"Mary Zheng\"},\"description\":\"Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Printf Java Example (with video) - Java Code Geeks","description":"Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","og_locale":"en_US","og_type":"article","og_title":"Printf Java Example (with video) - Java Code Geeks","og_description":"Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.","og_url":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2019-07-10T08:00:28+00:00","article_modified_time":"2022-07-05T20:11:03+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"Mary Zheng","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Mary Zheng","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/"},"author":{"name":"Mary Zheng","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae"},"headline":"Printf Java Example (with video)","datePublished":"2019-07-10T08:00:28+00:00","dateModified":"2022-07-05T20:11:03+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/"},"wordCount":1109,"commentCount":2,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/printf-java-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","url":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","name":"Printf Java Example (with video) - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2019-07-10T08:00:28+00:00","dateModified":"2022-07-05T20:11:03+00:00","description":"Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/printf-java-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"Printf Java Example (with video)"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae","name":"Mary Zheng","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg","caption":"Mary Zheng"},"description":"Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.","url":"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/74284","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/140"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=74284"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/74284\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=74284"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=74284"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=74284"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}