Title: Printf Java Example (with video) - Java Code Geeks
Open Graph 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.
Open Graph Description: Check out our Java example using the System.out.printf method. The printf method can format a string which contains formatting specifiers.
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/printf-java-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@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/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2019-07-10T11:00:28+03:00","datePublished":"2019-07-10T11:00:28+03:00","dateModified":"2022-07-05T23:11:03+03:00","headline":"Printf Java Example (with video)","name":"Printf Java Example (with video)","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","description":"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 whi","copyrightYear":"2019","articleSection":"Core Java","articleBody":"\nIn 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.\n\n\n\n1. Introduction\n\n\n\nThe Java PrintStream class has provided the printf method to write a formatted string to the PrintStream object since version 5. Here are the method's signatures:\n\n\n\npublic PrintStream printf(Locale l, String format, Object... args)\npublic PrintStream printf(String format, Object... args)\n\n\n\nl - a locale to apply during formattingformat - a format string as described in format string syntaxargs - arguments referenced by the format specifiers in the format string\n\n\n\n You can also check this tutorial in the following video: \n\n\n\nPrintf Java Example - Video\n\n\n\nThe printf method can format a string which contains formatting specifiers for Integer, float, Date, String, etc. The formatting specifiers start with % and is followed by four optional arguments and one mandatory conversion argument.\n\n\n\n%[argument_index$][flags][width][.precision]conversion\n\n\n\n\n\n\n\nargument_index - it is an optional decimal integer indicating the position of the argument in the argument list. The first argument is referenced by \"1$\", the second by \"2$\", etc.flags - it is an optional set of characters that modify the output format. The set of valid flags depends on the conversion.width - it is an optional positive decimal integer indicating the minimum number of characters to be written to the output.precision - it is an optional non-negative decimal integer used to restrict the number of characters.conversion - it is a mandatory character indicating how the argument should be formatted.\n\n\n\nIn this example, I will demonstrate how to format a string with these formatting specifiers.\n\n\n\n2. Technologies Used\n\n\n\nThe example code in this example was built and run with:\n\n\n\nJava 11Maven 3.3EclipseJunit 4.12\n\n\n\n3. Maven Project\n\n\n\n3.1 Dependencies\n\n\n\nI will include Junit in the pom.xml.\n\n\n\npom.xml\n\n\n\n\n<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\">\n\t<modelVersion>4.0.0<\/modelVersion>\n\t<groupId>java-printf-demo<\/groupId>\n\t<artifactId>java-printf-demo<\/artifactId>\n\t<version>0.0.1-SNAPSHOT<\/version>\n\t<build>\n\t\t<sourceDirectory>src<\/sourceDirectory>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin<\/artifactId>\n\t\t\t\t<version>3.8.0<\/version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<release>11<\/release>\n\t\t\t\t<\/configuration>\n\t\t\t<\/plugin>\n\t\t<\/plugins>\n\t<\/build>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit<\/groupId>\n\t\t\t<artifactId>junit<\/artifactId>\n\t\t\t<version>4.12<\/version>\n\t\t<\/dependency>\n\t<\/dependencies>\n<\/project>\n\n\n\n3.2 PrintfFormatBaseTest\n\n\n\nJava Formatter class defines the formatting specifiers. Here are some common conversion specifiers:\n\n\n\nb(B) - converts a non-null boolean or Boolean object base on String.valueOf(arg).c(C) - transforms a character based on its Unicodeh - translates based on the hashcode methodd - converts an integer numberf - converts a float numbern - converts to a platform-specific line separator s(S) - formats a Stringt(T) - converts to a date and time value\n\n\n\nThe following are some common flag specifiers:\n\n\n\n-: Left-justified+: Include a sign for a numeric value0: Zero-padding for a numeric value,: locale-specific grouping separators \n\n\n\nIn this example, I will create several constants which embed the format specifiers. I will use Junit @Rule to print out the test method's name. I will also create several test methods to demonstrate the three kinds of argument indexing:\n\n\n\nexplicit indexing - specifies the argument with explicit indexing, e.g. 1$ordinary indexing - the argument-index is based on the positionrelative indexing - uses the same argument with '<'\n\n\n\nIn the test methods I use the System.out.printf method.\n\n\n\nPrintfFormatBaseTest.java \n\n\n\npackage 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, %<s, %<s, %2$s, and %<s\", \"Zheng\", \"Mary\");\t \n\t}\n\t\n}\n\n\n\nExecute mvn test -Dtest=PrintfFormatBaseTest and capture the output.\n\n\n\nPrintfFormatBaseTest results.\n\n\n\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo>mvn test -Dtest=PrintfFormatBaseTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] -----------------< java-printf-demo:java-printf-demo >------------------\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>\n\n\n\n4. Format a Number\n\n\n\n4.1 Printf_NumberTest\n\n\n\nIn this step, I will create Junit tests to format a number in several ways:\n\n\n\nFormats a number (base 8, 10, and 16) for different data types: byte, short, int, and longFormats a float number in exponential formatFormats a decimal number for different data types: float and doubleFormats a decimal number with different padding characters: space and zeroFormats a float number with left-justified (-), sign (+), and comma (,) flag, 2 precision (.2), and width 10 specifiers\n\n\n\n In the test methods I use the System.out.printf method. \n\n\n\nPrintf_NumberTest.java \n\n\n\npackage 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\n\n\n\nExecute mvn test -Dtest=Printf_NumberTest and capture the output. \n\n\n\nPrintf_NumberTest results\n\n\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-printf-demo>mvn test -Dtest=Printf_NumberTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] -----------------< java-printf-demo:java-printf-demo >------------------\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>\n\n\n\n4.2 NumberFormatTest\n\n\n\nJava provides a NumberFormat 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 printf method with more readable code.\n\n\n\nNumberFormatTest.java \n\n\n\npackage 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\n\n\n\nExecute mvn test -Dtest=NumberFormatTest and capture the output. \n\n\n\nNumberFormatTest Output\n\n\n\n\n-------------------------------------------------------\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\n\n\n\n5. Format a Date\n\n\n\n5.1 Printf_DateTest\n\n\n\nJava provides additional specifier suffix after the date\/time conversation specifiers: t and T. \n\n\n\nHere are some common date suffix specifiers:\n\n\n\nm - Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 12d - Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31y - Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99Y - Year, formatted to at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar \n\n\n\nHere are some common time suffix specifiers:\n\n\n\nH - Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as necessary i.e. 00 - 23.M - Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.S - Seconds within the minute, formatted as two digits with a leading zero as necessary, i.e. 00 - 60 (\"60\" is a special value required to support leap seconds).r - a 12-hour clock time as \"%tI:%tM:%tS %Tp\" \n\n\n\nIn this step, I will create several test methods to format a date with the predefined format specifiers, using again the System.out.printf method. \n\n\n\nFormat a data time with tcformat a date with tDformat a ISO8601 date with tFFormat a 12 hour time with tr\n\n\n\nPrintf_DateTest.java \n\n\n\npackage 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\n\n\n\nExecute mvn test -Dtest=Printf_DateTest and capture the output. \n\n\n\nPrintf_DateTest Output\n\n\n\n\nRunning 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\n\n\n\n5.2 DateFormatTest\n\n\n\nJava provides a SimpleDateFormat and DateTimeFormatter class to format a date. Both classes have similar format specifiers, but the DateTimeFormatter 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.\n\n\n\nDateFormatTest.java \n\n\n\npackage 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\n\n\n\n Execute mvn test -Dtest=DateFormatTest and capture the output. \n\n\n\nDateFormatTest Output\n\n\n\n\n-------------------------------------------------------\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\n\n\n\n6. Format a String \n\n\n\n6.1 Printf_StringTest\n\n\n\nIn this step, I will create several Junit test methods to format a string with several conversion specifiers: %c, %b, %h, %s, and %S.\n\n\n\nPrintf_StringTest.java \n\n\n\npackage 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\n\n\n\n Execute mvn test -Dtest=Printf_StringTest and capture the output. \n\n\n\nPrintf_StringTest Output\n\n\n\n\nRunning 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\n\n\n\n6.2 Printf_FileTest\n\n\n\nIn this step, I will demonstrate how to write the formatted data to a text file with the printf method.\n\n\n\nPrintf_FileTest.java \n\n\n\npackage 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\n\n\n\nExecute mvn test -Dtest=Printf_FileTest and capture the content of Printf_demo.txt. \n\n\n\nPrintf_demo.txt\n\n\n\n\n%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\n\n\n\n7. Printf Java Example \u2013 Summary\n\n\n\nIn this example, I demonstrated how to use the printf method to:\n\n\n\nFormat a numberFormat a dateFormat a stringWrite to a file\n\n\n\nI also compared printf to NumberFormat, SimpleDateFormat, and DateTimeFormatter. It is important for the developers to know the printf format specifiers when using the System.out.printf method.\n\n\n\n8. More articles\n\n\n\nJava Tutorial for BeginnersArrayList Java Example \u2013 How to use arraylistHashmap Java ExampleJava Array \u2013 java.util.Arrays Example (with Video)Java String Class ExampleJava List Examplejava.util.Scanner \u2013 Scanner Java ExampleJava Map ExampleJava Queue ExampleJava Stack Example\n\n\n\n9. Download the Source Code\n\n\n\nThis was an example on Java printf() Method . This example consists of a Maven project which defines seven test classes to demonstrate the printf method's usages.\n\n\n\nDownload\nYou can download the full source code of this example here: Printf Java Example\n\n\n\nLast updated on May 31st, 2021\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/printf-java-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Mary Zheng","url":"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| 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 | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Mary Zheng |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Mary Zheng |
| twitter:label2 | Est. reading time |
| twitter:data2 | 14 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1