Printf Java Example (with video) (original) (raw)
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
object since version 5. Here are the method’s signatures:
public PrintStream printf(Locale l, String format, Object... args) public PrintStream printf(String format, Object... args)
l
– a locale to apply during formattingformat
– a format string as described in format string syntaxargs
– arguments referenced by the format specifiers in theformat
string
You can also check this tutorial in the following video:
Printf Java Example – Video
The 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.
%[argument_index$][flags][width][.precision]conversion
argument_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.
In this example, I will demonstrate how to format a string with these formatting specifiers.
2. Technologies Used
The example code in this example was built and run with:
- Java 11
- Maven 3.3
- Eclipse
- Junit 4.12
3. Maven Project
3.1 Dependencies
I will include Junit
in the pom.xml
.
pom.xml
4.0.0 java-printf-demo java-printf-demo 0.0.1-SNAPSHOT src maven-compiler-plugin 3.8.0 11 junit junit 4.12
3.2 PrintfFormatBaseTest
Java Formatter class defines the formatting specifiers. Here are some common conversion specifiers:
- b(B) – converts a non-null
boolean
orBoolean
object base onString.valueOf(arg)
. - c(C) – transforms a character based on its Unicode
- h – translates based on the
hashcode
method - d – converts an integer number
- f – converts a float number
- n – converts to a platform-specific line separator
- s(S) – formats a String
- t(T) – converts to a date and time value
The following are some common flag specifiers:
- -: Left-justified
- +: Include a sign for a numeric value
- 0: Zero-padding for a numeric value
- ,: locale-specific grouping separators
In 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:
- explicit indexing – specifies the argument with explicit indexing, e.g.
1$
- ordinary indexing – the argument-index is based on the position
- relative indexing – uses the same argument with
'<'
In the test methods I use the System.out.printf method.
PrintfFormatBaseTest.java
package jcg.zheng.demo;
import java.util.MissingFormatArgumentException;
import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description;
public class PrintfFormatBaseTest {
@Rule
public TestRule echoMethodName = new TestWatcher() {
protected void starting(Description desc) {
System.out.println("\nTestMethodName:" + desc.getMethodName());
}
};
protected static final String BOOLEAN_B = "%%b - format boolean value: %b, %%B - Boolean value: %B";
protected static final String CHAR_C = "%%c - format char with lower-case value: %c, %%C - with upper-case value: %C.";
protected static final String DECIMAL_F = "%%f - doubleValue is: %f. floatValue is: %f";
protected 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";
protected static final String DECIMAL_PADDING_BLANK = "%% 10.3f - Format a decimal with padding empty space: % 10.3f";
protected static final String DECIMAL_PADDING_ZERO = "%%010.3f - Format a decimal with padding zero: %010.3f";
protected static final String EXPONENTIAL_E = "%%e - exponential number. Value is: %e.";
protected static final String HASHCODE_H = "The string object's hashcode: %h, the interger's hashcode: %h";
protected static final String INTEGER_D_BASE10 = "%%d - byteValue is: %d, shortValue is: %d, intValue is: %d, longValue is: %d.";
protected static final String INTEGER_O_BASE8 = "%%o - Octal format. byteValue is: %o, shortValue is: %o, intValue is: %o, longValue is: %o.";
protected static final String INTEGER_X_BASE16 = "%%x - Base 16. byteValue is: %x, shortValue is: %x, intValue is: %x, longValue is: %x.";
protected static final String NEW_LINE = "%n";
protected byte byteValue = 12;
protected double doubleValue = 10.123;
protected float floatValue = 123.45f;
protected int intValue = 123;
protected long longValue = 1234567;
protected short shortValue = 121;
@Test
public void explicit_indexing_test() {
System.out.printf("explicit two arguments: %1$s, %2$s", "Hello", "World!");
}
@Test
public void explicit_indexing_test_differentOrder() {
System.out.printf("explicit two arguments: %2$s, %1$s", "Hao!", "Ni");
}
@Test(expected = MissingFormatArgumentException.class)
public void ordinary_indexing_test_exception() {
System.out.printf("throw MissingFormatArgumentException: %s, %s", "test");
}
@Test
public void relative_indexing_test() {
System.out.printf("relative arguments - %1$s, %<s, %<s, %2$s, and %<s", "Zheng", "Mary");
}
}
Execute mvn test -Dtest=PrintfFormatBaseTest
and capture the output.
PrintfFormatBaseTest results.
C:\MaryZheng\Workspaces\jdk12\java-printf-demo>mvn test -Dtest=PrintfFormatBaseTest [INFO] Scanning for projects... [INFO] [INFO] -----------------< java-printf-demo:java-printf-demo >------------------ [INFO] Building java-printf-demo 0.0.1-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-printf-demo --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-printf-demo\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-printf-demo --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 7 source files to C:\MaryZheng\Workspaces\jdk12\java-printf-demo\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-printf-demo --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-printf-demo\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-printf-demo --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 7 source files to C:\MaryZheng\Workspaces\jdk12\java-printf-demo\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-printf-demo --- [INFO] Surefire report directory: C:\MaryZheng\Workspaces\jdk12\java-printf-demo\target\surefire-reports
T E S T S
Running jcg.zheng.demo.PrintfFormatBaseTest
TestMethodName:explicit_indexing_test_differentOrder explicit two arguments: Ni, Hao! TestMethodName:relative_indexing_test relative arguments - Zheng, Zheng, Zheng, Mary, and Mary TestMethodName:explicit_indexing_test explicit two arguments: Hello, World! TestMethodName:ordinary_indexing_test_exception throw MissingFormatArgumentException: test, Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.157 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 10.262 s [INFO] Finished at: 2019-07-07T11:50:17-05:00 [INFO] ------------------------------------------------------------------------
C:\MaryZheng\Workspaces\jdk12\java-printf-demo>
4. Format a Number
4.1 Printf_NumberTest
In this step, I will create Junit tests to format a number in several ways:
- Formats a number (base 8, 10, and 16) for different data types:
byte
,short
,int
, andlong
- Formats a float number in exponential format
- Formats a decimal number for different data types:
float
anddouble
- Formats a decimal number with different padding characters: space and zero
- Formats a float number with left-justified (-), sign (+), and comma (,) flag, 2 precision (.2), and width 10 specifiers
In the test methods I use the System.out.printf method.
Printf_NumberTest.java
package jcg.zheng.demo;
import org.junit.Test;
public class Printf_NumberTest extends PrintfFormatBaseTest {
@Test
public void d_for_integer_base10() {
System.out.printf(INTEGER_D_BASE10, byteValue, shortValue, intValue, longValue);
}
@Test
public void e_for_exponential_number() {
System.out.printf(EXPONENTIAL_E, floatValue);
}
@Test
public void f_for_decimal() {
System.out.printf(DECIMAL_F, doubleValue, floatValue);
}
@Test
public void o_for_integer_base8() {
System.out.printf(INTEGER_O_BASE8, byteValue, shortValue, intValue, longValue);
}
@Test
public void padding_space() {
// % 10.3f - Format a decimal with padding empty space: 125.100
System.out.printf(DECIMAL_PADDING_BLANK, 125.1f);
}
@Test
public void padding_zero() {
// %010.3f - Format a decimal with padding zero: 000125.100
System.out.printf(DECIMAL_PADDING_ZERO, 125.1f);
}
@Test
public void with_all_formatting_flags_width_precision() {
// %-+,10.2f - Format a negative number by left-justified, separating with comma,
// with a sign, 10 width, and 2 precision: -12,345.12
System.out.printf(DECIMAL_FLAGS_WIDTH_PRECISION, -12345.1234f);
}
@Test
public void x_for_integer_base16() {
System.out.printf(INTEGER_X_BASE16, byteValue, shortValue, intValue, longValue);
}
}
Execute mvn test -Dtest=Printf_NumberTest
and capture the output.
Printf_NumberTest results
C:\MaryZheng\Workspaces\jdk12\java-printf-demo>mvn test -Dtest=Printf_NumberTest [INFO] Scanning for projects... [INFO] [INFO] -----------------< java-printf-demo:java-printf-demo >------------------ [INFO] Building java-printf-demo 0.0.1-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-printf-demo --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-printf-demo\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-printf-demo --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 7 source files to C:\MaryZheng\Workspaces\jdk12\java-printf-demo\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-printf-demo --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-printf-demo\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-printf-demo --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-printf-demo --- [INFO] Surefire report directory: C:\MaryZheng\Workspaces\jdk12\java-printf-demo\target\surefire-reports
T E S T S
Running jcg.zheng.demo.Printf_NumberTest
TestMethodName:d_for_integer_base10 %d - byteValue is: 12, shortValue is: 121, intValue is: 123, longValue is: 1234567. TestMethodName:x_for_integer_base16 %x - Base 16. byteValue is: c, shortValue is: 79, intValue is: 7b, longValue is: 12d687. TestMethodName:o_for_integer_base8 %o - Octal format. byteValue is: 14, shortValue is: 171, intValue is: 173, longValue is: 4553207. TestMethodName:e_for_exponential_number %e - exponential number. Value is: 1.234500e+02. TestMethodName:f_for_decimal %f - doubleValue is: 10.123000. floatValue is: 123.449997 TestMethodName:with_all_formatting_flags_width_precision %-+,10.2f - Format a negative number by left-justified, separating with comma, with a sign, 10 width, and 2 precision: -12,345.12 TestMethodName:padding_zero %010.3f - Format a decimal with padding zero: 000125.100 TestMethodName:padding_space % 10.3f - Format a decimal with padding empty space: 125.100 TestMethodName:explicit_indexing_test_differentOrder explicit two arguments: Ni, Hao! TestMethodName:relative_indexing_test relative arguments - Zheng, Zheng, Zheng, Mary, and Mary TestMethodName:explicit_indexing_test explicit two arguments: Hello, World! TestMethodName:ordinary_indexing_test_exception throw MissingFormatArgumentException: test, Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.193 sec
Results :
Tests run: 12, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 8.983 s [INFO] Finished at: 2019-07-07T11:52:47-05:00 [INFO] ------------------------------------------------------------------------
C:\MaryZheng\Workspaces\jdk12\java-printf-demo>
4.2 NumberFormatTest
Java 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.
NumberFormatTest.java
package jcg.zheng.demo;
import static org.junit.Assert.assertEquals;
import java.text.NumberFormat; import java.util.Locale;
import org.junit.Test;
public class NumberFormatTest {
private NumberFormat usNumFormat = NumberFormat.getInstance(new Locale("en", "US"));;
@Test
public void formatDecimal() {
usNumFormat.setMaximumFractionDigits(4);
usNumFormat.setMinimumFractionDigits(2);
assertEquals("123.4568", usNumFormat.format(123.45678));
}
@Test
public void formatInteger() {
assertEquals("100", usNumFormat.format(100l));
}
@Test
public void formatPercentage() {
NumberFormat nf = NumberFormat.getPercentInstance();
assertEquals("25%", nf.format(0.25));
}
}
Execute mvn test -Dtest=NumberFormatTest
and capture the output.
NumberFormatTest Output
T E S T S
Running jcg.zheng.demo.NumberFormatTest Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.174 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
5. Format a Date
5.1 Printf_DateTest
Java provides additional specifier suffix after the date/time conversation specifiers: t
and T
.
Here are some common date suffix specifiers:
m
– 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
Here are some common time suffix specifiers:
H
– 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"
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.
- Format a data time with
tc
- format a date with
tD
- format a ISO8601 date with
tF
- Format a 12 hour time with
tr
Printf_DateTest.java
package jcg.zheng.demo;
import java.util.Date;
import org.junit.Test;
public class Printf_DateTest extends PrintfFormatBaseTest {
@Test
public void tc_detail_date_time() {
// DateTime: Mon Jul 01 23:09:59 CDT 2019
System.out.printf("DateTime: %1$tc", new Date());
}
@Test
public void Tc_detail_date_time() {
// DateTime: SUN JUL 07 07:19:32 CDT 2019
System.out.printf("DateTime: %1$Tc", new Date());
}
@Test
public void tD_month_day_year() {
// Date: 07/01/19
System.out.printf("Date: %1$tD", new Date());
}
@Test
public void dateTime_format_explicating_indexing() {
// Time: 01-07-2019 22:54:31
// td day of month
System.out.printf("Time: %1$td-%1$tm-%1$tY %1$tH:%1$tM:%1$tS", new Date());
}
@Test
public void dateTime_format_explicating_indexing_2() {
// Date: July 01 2019
// tB local-specific full month name
System.out.printf("Date: %1$tB %1$td %1$tY", new Date());
}
@Test
public void tF_ISO8601() {
// Date: 2019-07-01
System.out.printf("Date: %1$tF", new Date());
}
@Test
public void tR_Hour_Minute() {
// tH:tM
System.out.printf("Date: %1$tR", new Date());
}
@Test
public void tr_Hour_Minute_Second_12() {
// Time: 11:07:18 PM
// tH:tM:tS
System.out.printf("Time: %1$tr", new Date());
}
@Test
public void tT_Hour_Minute_Second() {
// tH:tM:tS
System.out.printf("Date: %1$tT", new Date());
}
}
Execute mvn test -Dtest=Printf_DateTest
and capture the output.
Printf_DateTest Output
Running jcg.zheng.demo.Printf_DateTest
TestMethodName:tr_Hour_Minute_Second_12 Time: 12:00:29 PM TestMethodName:tR_Hour_Minute Date: 12:00 TestMethodName:dateTime_format_explicating_indexing_2 Date: July 07 2019 TestMethodName:dateTime_format_explicating_indexing Time: 07-07-2019 12:00:29 TestMethodName:tD_month_day_year Date: 07/07/19 TestMethodName:tc_detail_date_time DateTime: Sun Jul 07 12:00:29 CDT 2019 TestMethodName:tT_Hour_Minute_Second Date: 12:00:29 TestMethodName:Tc_detail_date_time DateTime: SUN JUL 07 12:00:29 CDT 2019 TestMethodName:tF_ISO8601 Date: 2019-07-07 TestMethodName:explicit_indexing_test_differentOrder explicit two arguments: Ni, Hao! TestMethodName:relative_indexing_test relative arguments - Zheng, Zheng, Zheng, Mary, and Mary TestMethodName:explicit_indexing_test explicit two arguments: Hello, World! TestMethodName:ordinary_indexing_test_exception throw MissingFormatArgumentException: test, Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.364 sec
Results :
Tests run: 13, Failures: 0, Errors: 0, Skipped: 0
5.2 DateFormatTest
Java 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.
DateFormatTest.java
package jcg.zheng.demo;
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.GregorianCalendar;
import org.junit.Test;
public class DateFormatTest {
@Test
public void dateTimeFormat() {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
System.out.println(df.format((new GregorianCalendar()).getTime()));
}
@Test
public void DateTimeFormatter_java8() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime now = LocalDateTime.now();
System.out.println("default format:" + now);
String formatDateTime = now.format(formatter);
System.out.println("ISO_DATE_TIME format : " + formatDateTime);
}
}
Execute mvn test -Dtest=DateFormatTest
and capture the output.
DateFormatTest Output
T E S T S
Running jcg.zheng.demo.DateFormatTest default format:2019-07-07T12:03:39.023577700 ISO_DATE_TIME format : 2019-07-07T12:03:39.0235777 07-07-2019 12:03:39 Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.242 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
6. Format a String
6.1 Printf_StringTest
In this step, I will create several Junit test methods to format a string with several conversion specifiers: %c, %b, %h, %s, and %S.
Printf_StringTest.java
package jcg.zheng.demo;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
public class Printf_StringTest extends PrintfFormatBaseTest {
private boolean isFalse = false;
private Boolean isTrue = Boolean.TRUE;
@Test
public void b_for_boolean() throws UnsupportedEncodingException {
System.out.printf(BOOLEAN_B, isFalse, isTrue);
}
@Test
public void b_for_String_always_True() throws UnsupportedEncodingException {
System.out.printf(BOOLEAN_B, "test", 1);
}
@Test
public void c_for_character() {
System.out.printf(CHAR_C, 'm', 'm');
}
@Test
public void h_for_hashcode() {
String s = "Hello World";
Integer number = Integer.valueOf(100);
System.out.printf(HASHCODE_H, s, number);
}
@Test
public void n_for_newline() {
System.out.printf("Hello World%n2nd line");
}
@Test
public void s_for_string() {
String stringVal = "Hi, Mary!";
System.out.printf("Left-justified is: %-20s\n", stringVal);
System.out.printf("Uppercase, Right-justified is: %20S\n", stringVal);
}
@Test
public void s_for_string_width_too_small() {
String stringVal = "Hi, Mary!";
System.out.printf("width is smaller: %2S", stringVal);
}
}
Execute mvn test -Dtest=Printf_StringTest
and capture the output.
Printf_StringTest Output
Running jcg.zheng.demo.Printf_StringTest
TestMethodName:b_for_String_always_True %b - format boolean value: true, %B - Boolean value: TRUE TestMethodName:s_for_string_width_too_small width is smaller: HI, MARY! TestMethodName:n_for_newline Hello World 2nd line TestMethodName:h_for_hashcode The string object's hashcode: cc969a84, the interger's hashcode: 64 TestMethodName:b_for_boolean %b - format boolean value: false, %B - Boolean value: TRUE TestMethodName:s_for_string Left-justified is: Hi, Mary! Uppercase, Right-justified is: HI, MARY!
TestMethodName:c_for_character %c - format char with lower-case value: m, %C - with upper-case value: M. TestMethodName:explicit_indexing_test_differentOrder explicit two arguments: Ni, Hao! TestMethodName:relative_indexing_test relative arguments - Zheng, Zheng, Zheng, Mary, and Mary TestMethodName:explicit_indexing_test explicit two arguments: Hello, World! TestMethodName:ordinary_indexing_test_exception throw MissingFormatArgumentException: test, Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.211 sec
Results :
Tests run: 11, Failures: 0, Errors: 0, Skipped: 0
6.2 Printf_FileTest
In this step, I will demonstrate how to write the formatted data to a text file with the printf
method.
Printf_FileTest.java
package jcg.zheng.demo;
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Date;
import org.junit.Test;
public class Printf_FileTest extends PrintfFormatBaseTest {
@Test
public void writetoFile() {
PrintStream writeToFile;
try {
writeToFile = new PrintStream(new FileOutputStream("Printf_demo.txt", true));
writeToFile.printf(BOOLEAN_B, false, Boolean.TRUE);
writeToFile.printf(NEW_LINE);
writeToFile.printf(CHAR_C, 'a', 'a');
writeToFile.printf(NEW_LINE);
writeToFile.printf("%%-20s - Format string with Left-justified and 20 width is: %-20s", "Mary Zheng");
writeToFile.printf(NEW_LINE);
writeToFile.printf("%%20S - Format string with Uppercase, Right-justified : %20S", "Hello");
writeToFile.printf(NEW_LINE);
writeToFile.printf(DECIMAL_F, doubleValue, floatValue);
writeToFile.printf(NEW_LINE);
writeToFile.printf(EXPONENTIAL_E, floatValue);
writeToFile.printf(NEW_LINE);
writeToFile.printf(INTEGER_D_BASE10, byteValue, shortValue, intValue, longValue);
writeToFile.printf(NEW_LINE);
writeToFile.printf(INTEGER_O_BASE8, byteValue, shortValue, intValue, longValue);
writeToFile.printf(NEW_LINE);
writeToFile.printf(INTEGER_X_BASE16, byteValue, shortValue, intValue, longValue);
writeToFile.printf(NEW_LINE);
writeToFile.printf(DECIMAL_PADDING_BLANK, 125.1f);
writeToFile.printf(NEW_LINE);
writeToFile.printf(DECIMAL_PADDING_ZERO, 125.1f);
writeToFile.printf(NEW_LINE);
writeToFile.printf(DECIMAL_FLAGS_WIDTH_PRECISION, -12345.1234f);
writeToFile.printf(NEW_LINE);
writeToFile.printf("%%1$tc - Format a DateTime: %1$tc", new Date());
writeToFile.printf(NEW_LINE);
writeToFile.printf("%%1$tD - Format a Date: %1$tD", new Date());
writeToFile.printf(NEW_LINE);
writeToFile.printf("%%1$tT - Format a Time: %1$tT", new Date());
writeToFile.printf(NEW_LINE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Execute mvn test -Dtest=Printf_FileTest
and capture the content of Printf_demo.txt
.
Printf_demo.txt
%b - format boolean value: false, %B - Boolean value: TRUE
%c - format char with lower-case value: a, %C - with upper-case value: A.
%-20s - Format string with Left-justified and 20 width is: Mary Zheng
%20S - Format string with Uppercase, Right-justified : HELLO
%f - doubleValue is: 10.123000. floatValue is: 123.449997
%e - exponential number. Value is: 1.234500e+02.
%d - byteValue is: 12, shortValue is: 121, intValue is: 123, longValue is: 1234567.
%o - Octal format. byteValue is: 14, shortValue is: 171, intValue is: 173, longValue is: 4553207.
%x - Base 16. byteValue is: c, shortValue is: 79, intValue is: 7b, longValue is: 12d687.
% 10.3f - Format a decimal with padding empty space: 125.100
%010.3f - Format a decimal with padding zero: 000125.100
%-+,10.2f - Format a negative number by left-justified, separating with comma, with a sign, 10 width, and 2 precision: -12,345.12
%1$tc - Format a DateTime: Sun Jul 07 12:06:42 CDT 2019
%1$tD - Format a Date: 07/07/19
%1$tT - Format a Time: 12:06:42
7. Printf Java Example – Summary
In this example, I demonstrated how to use the printf
method to:
- Format a number
- Format a date
- Format a string
- Write to a file
I 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.
8. More articles
- Java Tutorial for Beginners
- ArrayList Java Example – How to use arraylist
- Hashmap Java Example
- Java Array – java.util.Arrays Example (with Video)
- Java String Class Example
- Java List Example
- java.util.Scanner – Scanner Java Example
- Java Map Example
- Java Queue Example
- Java Stack Example
9. Download the Source Code
This 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.
Download
You can download the full source code of this example here: Printf Java Example
Last updated on May 31st, 2021