Notes

Java - Formatter

author: Paul Kim

categories: java

tags: java

Formatting

// write to output stream using PrintStream's printf and format
int i = 2;
double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n", i, r);
System.out.printf("%s%n", "hello");

System.err.format("Unable to open file '%s': %s%n", "filename.txt", "there was a problem");
System.err.printf("We got %s... I mean, %d more problem%n", "another", 1);

// return string using String.format
String s = String.format("%d", 123);
System.out.println(s);

// build string using Formatter
Formatter formatter = new Formatter();
formatter.format("%s", "world");
System.out.println(formatter);
formatter.flush();
formatter.format("%d", 123);
System.out.println(formatter);
formatter.flush();

Conversions

Conversions are divided into the following categories:

  • General (%b %B %h %H %s %S) - may be applied to any argument type
  • Character (%c %C) - may be applied to basic types which represent Unicode characters: char, Character, byte, Byte, short, and Short. This conversion may also be applied to the types int and Integer when Character.isValidCodePoint(int) returns true
  • Numeric

    • Integral (%d %o %x %X) - may be applied to Java integral types: byte, Byte, short, Short, int and Integer, long, Long, and BigInteger (but not char or Character)
    • Floating Point (%e %E %f %g %G %a %A) - may be applied to Java floating-point types: float, Float, double, Double, and BigDecimal
  • Date/Time (%t %T) - may be applied to Java types which are capable of encoding a date or time: long, Long, Calendar, Date and TemporalAccessor
  • Percent (%%) - produces a literal '%' ('\u0025')
  • Line Separator (%n) - produces the platform-specific line separator

Note: (%B %H %S %C %X %E %G %A %T) are the same as (%b %h %s %c %x %e %g %a %t) except that the result is converted to upper case according to the rules of the prevailing Locale.

General Conversions

Conversion Description
%b %B If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is "true".
%h %H If the argument arg is null, then the result is "null". Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()).
%s %S If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().
// %b
System.out.format("%b%n", (Object) null); // false
System.out.format("%b%n", false); // false
System.out.format("%b%n", true); // true
System.out.format("%b%n", Integer.MIN_VALUE); // true
System.out.format("%b%n", -1); // true
System.out.format("%b%n", 0); // true
System.out.format("%b%n", 1); // true
System.out.format("%b%n", Integer.MAX_VALUE); // true

// %B
System.out.format("%B%n", (Object) null); // FALSE
System.out.format("%9B%n", false); // "    FALSE"
System.out.format("%-9Bending%n", true); // "TRUE     ending"
System.out.format("%B%n", Integer.MIN_VALUE); // TRUE
System.out.format("%B%n", -1); // TRUE
System.out.format("%B%n", 0); // TRUE
System.out.format("%B%n", 1); // TRUE
System.out.format("%B%n", Integer.MAX_VALUE); // TRUE

// %h
System.out.format("%h%n", (Object) null); // null
System.out.format("%h%n", "hello world"); // 6aefe2c4

// %H
System.out.format("%H%n", (Object) null); // null
System.out.format("%H%n", "hello world"); // 6AEFE2C4

// %s
System.out.format("%s%n", "hello"); // hello

// %S
System.out.format("%S%n", "hello"); // HELLO

Character Conversions

Conversion Description
%c %C The result is a Unicode character
// %c %C
System.out.format("%c%n", null);
System.out.format("%c%n", 'a'); // a
System.out.format("%C%n", 'a'); // A
System.out.format("%c%n", 0x00E0); // à
System.out.format("%C%n", 0x00E0); // À
System.out.format("%c%n", '\u00E0'); // à
System.out.format("%C%n", '\u00E0'); // À
System.out.format("%c%n", 0x0450); // ѐ
System.out.format("%C%n", 0x0450); // Ѐ
System.out.format("%c%n", '\u0450'); // ѐ
System.out.format("%C%n", '\u0450'); // Ѐ
System.out.format("%c%c%c%n", '\uae40', '\ubc14', '\uc6b8'); // 김바울
int i = 9812;                           // 9812
int i2 = 1058388;                       // 1058388

char c = '♔';                           // ♔
char ci = 9812;                         // ♔
char ci2 = (char) i;                    // ♔
char ci3 = (char) i2;                   // ♔
char ch = 0x2654;                       // ♔
char cu = '\u2654';                     // ♔

String hs = Integer.toHexString(c);     // 2654
String hs2 = String.format("%h", c);    // 2654

System.out.format("%d %n", (int) c);    // 9812
System.out.format("%d %n", (int) ci);   // 9812
System.out.format("%d %n", (int) ci2);  // 9812
System.out.format("%d %n", (int) ci3);  // 9812
System.out.format("%d %n", (int) ch);   // 9812
System.out.format("%d %n", (int) cu);   // 9812
System.out.format("%d %n", i);          // 9812

System.out.format("%c %n", c);          // ♔
System.out.format("%c %n", ci);         // ♔
System.out.format("%c %n", ci2);        // ♔
System.out.format("%c %n", ci3);        // ♔
System.out.format("%c %n", ch);         // ♔
System.out.format("%c %n", cu);         // ♔
System.out.format("%c %n", i);          // ♔

System.out.format("%h %n", c);          // 2654
System.out.format("%h %n", ci);         // 2654
System.out.format("%h %n", ci2);        // 2654
System.out.format("%h %n", ci3);        // 2654
System.out.format("%h %n", ch);         // 2654
System.out.format("%h %n", cu);         // 2654
System.out.format("%h %n", i);          // 2654

System.out.format("%x %n", (int) c);    // 2654
System.out.format("%x %n", (int) ci);   // 2654
System.out.format("%x %n", (int) ci2);  // 2654
System.out.format("%x %n", (int) ci3);  // 2654
System.out.format("%x %n", (int) ch);   // 2654
System.out.format("%x %n", (int) cu);   // 2654
System.out.format("%x %n", i);          // 2654

System.out.format("\\u%h %n", i);       // \u2654
System.out.format("\\u%x %n", i);       // \u2654
System.out.format("%#x %n", i);         // 0x2654
System.out.format("%#X %n", i);         // 0X2654
char[] dash1 = {8211, 8212};
char[] dash2 = {0x2013, 0x2014};
char[] dash3 = {'\u2013', '\u2014'};
System.out.println(Arrays.toString(dash1)); // [–, —]
System.out.println(Arrays.toString(dash2)); // [–, —]
System.out.println(Arrays.toString(dash3)); // [–, —]

char[] whiteChessPieces1 = {9812, 9813, 9814, 9815, 9816, 9817};
char[] whiteChessPieces2 = {0x2654, 0x2655, 0x2656, 0x2657, 0x2658, 0x2659};
char[] whiteChessPieces3 = {'\u2654', '\u2655', '\u2656', '\u2657', '\u2658', '\u2659'};
System.out.println(Arrays.toString(whiteChessPieces1)); // [♔, ♕, ♖, ♗, ♘, ♙]
System.out.println(Arrays.toString(whiteChessPieces2)); // [♔, ♕, ♖, ♗, ♘, ♙]
System.out.println(Arrays.toString(whiteChessPieces3)); // [♔, ♕, ♖, ♗, ♘, ♙]

char[] blackChessPieces1 = {9818, 9819, 9820, 9821, 9822, 9823};
char[] blackChessPieces2 = {0x265a, 0x265b, 0x265c, 0x265d, 0x265e, 0x265f};
char[] blackChessPieces3 = {'\u265a', '\u265b', '\u265c', '\u265d', '\u265e', '\u265f'};
System.out.println(Arrays.toString(blackChessPieces1)); // [♚, ♛, ♜, ♝, ♞, ♟]
System.out.println(Arrays.toString(blackChessPieces2)); // [♚, ♛, ♜, ♝, ♞, ♟]
System.out.println(Arrays.toString(blackChessPieces3)); // [♚, ♛, ♜, ♝, ♞, ♟]

char[] blackSuits = {9824, 9827, 9829, 9830}; // spade, club, heart, diamond
System.out.println(Arrays.toString(blackSuits)); // [♠, ♣, ♥, ♦]

char[] whiteSuits = {9828, 9831, 9825, 9826}; // spade, club, heart, diamond
System.out.println(Arrays.toString(whiteSuits)); // [♤, ♧, ♡, ♢]
// create array of int ranging from 1 to 10
int[] range = IntStream.rangeClosed(1, 10).toArray();
System.out.println(Arrays.toString(range)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// create array of int ranging from 1 to 10
int[] range2 = IntStream.iterate(1, n -> n + 1).limit(10).toArray();
System.out.println(Arrays.toString(range2)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// create array of int ranging from 1 to 10
int[] arr = new int[10];
Arrays.setAll(arr, i -> i + 1);
System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]




// create array of int ranging from 9812 to 9817
int[] range3 = IntStream.rangeClosed(9812, 9817).toArray();
System.out.println(Arrays.toString(range3)); // [9812, 9813, 9814, 9815, 9816, 9817]

// create array of int ranging from 9812 to 9817
int[] range4 = IntStream.iterate(9812, n -> n + 1).limit(6).toArray();
System.out.println(Arrays.toString(range4)); // [9812, 9813, 9814, 9815, 9816, 9817]

// create list of Integer ranging from 9812 to 9817
List<Integer> list = IntStream.rangeClosed(9812, 9817)
        .boxed()
        .collect(Collectors.toList());
System.out.println(list); // [9812, 9813, 9814, 9815, 9816, 9817]

// create list of Integer ranging from 9812 to 9817
List<Integer> list2 = IntStream.iterate(9812, n -> n + 1).limit(6)
        .boxed()
        .collect(Collectors.toList());
System.out.println(list2); // [9812, 9813, 9814, 9815, 9816, 9817]




// create array of char ranging from 9812 to 9817
char[] range5 = IntStream.rangeClosed(9812, 9817)
        .mapToObj(c -> Character.toString((char) c))
        .collect(Collectors.joining())
        .toCharArray();
System.out.println(Arrays.toString(range5)); // [♔, ♕, ♖, ♗, ♘, ♙]

// create array of char ranging from 9812 to 9817
char[] range6 = IntStream.rangeClosed(9812, 9817)
        .mapToObj(c -> (char) c)
        .map(String::valueOf)
        .collect(Collectors.joining())
        .toCharArray();
System.out.println(Arrays.toString(range6)); // [♔, ♕, ♖, ♗, ♘, ♙]

// create array of char ranging from 9812 to 9817
char[] range7 = IntStream.iterate(9812, n -> n + 1).limit(6)
        .mapToObj(c -> Character.toString((char) c))
        .collect(Collectors.joining())
        .toCharArray();
System.out.println(Arrays.toString(range7)); // [♔, ♕, ♖, ♗, ♘, ♙]

List<Character> list4 = IntStream.rangeClosed(9812, 9817)
        .mapToObj(c -> (char)c)
        .collect(Collectors.toList());
System.out.println(list4); // [♔, ♕, ♖, ♗, ♘, ♙]

List<Character> list3 = IntStream.iterate(9812, n -> n + 1).limit(6)
        .mapToObj(c -> (char) c)
        .collect(Collectors.toList());
System.out.println(list3); // [♔, ♕, ♖, ♗, ♘, ♙]

Numeric Integral Conversions

Conversion Description
%d The result is formatted as a decimal integer
%o The result is formatted as an octal integer
%x %X The result is formatted as a hexadecimal integer
// %d
System.out.format("%,d%n", 461012); // " 461,012"
System.out.format(Locale.US, "%,d%n", 461012); // " 461,012"
System.out.format(Locale.FRANCE, "%,d%n", 461012); // " 461,012"
System.out.format(Locale.GERMANY, "%,d%n", 461012); // " 461.012"

Numeric Floating Point Conversions

Conversion Description
%e %E The result is formatted as a decimal number in computerized scientific notation
%f The result is formatted as a decimal number
%g %G The result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
%a %A The result is formatted as a hexadecimal floating-point number with a significand and an exponent

Date/Time Conversions

Conversion Description
%t %T Prefix for date and time conversion characters.
// Date c = new Date();
Calendar c = Calendar.getInstance();
// LocalDateTime c = LocalDateTime.now(); // does not work with %tz %tZ %ts %tQ %tc

// FORMATTING TIME

// %tH - Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as necessary (e.g. 00 - 23)
System.out.format("%tH hour%n", c);
// %tI - Hour for the 12-hour clock, formatted as two digits with a leading zero as necessary (i.e. 01 - 12)
System.out.format("%tI hour%n", c);
// %tk - Hour of the day for the 24-hour clock (i.e. 0 - 23)
System.out.format("%tk hour%n", c);
// %tl - Hour for the 12-hour clock (i.e. 1 - 12)
System.out.format("%tl hour%n", c);

// %tM - Minute within the hour formatted as two digits with a leading zero as necessary (i.e. 00 - 59)
System.out.format("%tM minutes%n", c);

// %tS - Second 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
System.out.format("%tS seconds%n", c);

// %tL - Millisecond within the second formatted as three digits with leading zeros as necessary (i.e. 000 - 999)
System.out.format("%tL milliseconds%n", c);

// %tN - Nanosecond within the second, formatted as nine digits with leading zeros as necessary (i.e. 000000000 - 999999999)
System.out.format("%tN nanoseconds%n", c);

// %tp - Locale-specific morning or afternoon marker in lower case (e.g. "am" or "pm")
System.out.format("%tp%n", c);

// %Tp - Locale-specific morning or afternoon marker in upper case (e.g. "AM" or "PM")
System.out.format("%Tp%n", c);

// %tz - RFC 822 style numeric time zone offset from GMT (e.g. -0800).
// This value will be adjusted as necessary for Daylight Saving Time.
// For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
System.out.format("%tz - RFC 822 style numeric time zone offset from GMT%n", c);

// %tZ - A string representing the abbreviation for the time zone.
// This value will be adjusted as necessary for Daylight Saving Time.
// For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
// The Formatter's locale will supersede the locale of the argument (if any).
System.out.format("%tZ - time zone abbreviation%n", c);

// %ts - Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC (i.e. Long.MIN_VALUE/1000 to Long.MAX_VALUE/1000)
System.out.format("%ts - seconds since the beginning of the epoch%n", c);

// %tQ - Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC (i.e. Long.MIN_VALUE to Long.MAX_VALUE)
System.out.format("%tQ - milliseconds since the beginning of the epoch%n", c);

// FORMATTING DATE

// %tB - locale-specific full month name (e.g. January, February)
System.out.format("%tB%n", c);
// %TB - locale-specific full month name (e.g. JANUARY, FEBRUARY)
System.out.format("%TB%n", c);
// %tb - locale-specific abbreviated month name (e.g. Jan, Feb)
System.out.format("%tb%n", c);
// %Tb - locale-specific abbreviated month name (e.g. JAN, FEB)
System.out.format("%Tb%n", c);
// %th - same as '%tb' (e.g. Jan, Feb)
System.out.format("%th%n", c);
// %Th - same as '%Tb' (e.g. JAN, FEB)
System.out.format("%Th%n", c);

// %tA - locale-specific full name of the day of the week (e.g. Sunday, Monday)
System.out.format("%tA%n", c);
// %TA - locale-specific full name of the day of the week (e.g. SUNDAY, MONDAY)
System.out.format("%TA%n", c);
// %ta - locale-specific short name of the day of the week (e.g. Sun, Mon)
System.out.format("%ta%n", c);
// %Ta - locale-specific short name of the day of the week (e.g. SUN, MON)
System.out.format("%Ta%n", c);

// %tC - Four-digit year divided by 100, formatted as two digits with leading zero as necessary (i.e. 00 - 99)
System.out.format("%tC - year (first two digits) (00 - 99)%n", c);
// %tY - Year, formatted as at least four digits with leading zeros as necessary (e.g. 0092 equals 92 CE for the Gregorian calendar)
System.out.format("%tY - year (four digits) (0000 - 9999)%n", c);
// %ty - Last two digits of the year, formatted with leading zeros as necessary (i.e. 00 - 99)
System.out.format("%ty - year (last two digits) (00 - 99)%n", c);

// %tj - Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366 for the Gregorian calendar.
System.out.format("%tj - day of year (001 - 366)%n", c);

// %tm - Month, formatted as two digits with leading zeros (i.e., 01 - 13)
System.out.format("%tm - month (two digits)%n", c);

// %td - Day of month, formatted as two digits with leading zeros as necessary (i.e., 01 - 31)
System.out.format("%td - day of month (01 - 31)%n", c);
// %te - Day of month formatted as two digits (i.e., 1 - 31)
System.out.format("%te - day of month (1 - 31)%n", c);

// %tR - Time formatted for the 24-hour clock as "%tH:%tM"
System.out.format("%tR - time formatted HH:MM%n", c);

// %tT - Time formatted for the 24-hour clock as "%tH:%tM:%tS"
System.out.format("%tT - time formatted HH:MM:SS%n", c);

// %tr - Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp". The location of the morning or afternoon marker ('%Tp') may be locale-dependent
System.out.format("%tr - time formatted HH:MM:SS AM/PM%n", c);

// %tD - Date formatted as "%tm/%td/%ty"
System.out.format("%tD - date formatted as MM/DD/YY%n", c);

// %tF - ISO 8601 complete date formatted as "%tY-%tm-%td"
System.out.format("%tF - date formatted as YYY-MM-DD%n", c);

// %tc - Date and time formatted as "%ta %tb %td %tT %tZ %tY", e.g. "Sun Jul 20 16:17:00 EDT 1969"
System.out.format("%tc - dated formatted as e.g. Sun Jul 20 16:17:00 EDT 1969%n", c);

Percent

Conversion Description
%% The result is a literal '%' ('\u0025')
// %%
System.out.format("100%%"); // 100%

Line Separator

Conversion Description
%n The result is the platform-specific line separator
// %n
System.out.format("hello%never");
// hello
// ever
Source

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.