Formatter.java revision 11357:97b8292cdd51
1/*
2 * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.util;
27
28import java.io.BufferedWriter;
29import java.io.Closeable;
30import java.io.IOException;
31import java.io.File;
32import java.io.FileOutputStream;
33import java.io.FileNotFoundException;
34import java.io.Flushable;
35import java.io.OutputStream;
36import java.io.OutputStreamWriter;
37import java.io.PrintStream;
38import java.io.UnsupportedEncodingException;
39import java.math.BigDecimal;
40import java.math.BigInteger;
41import java.math.MathContext;
42import java.math.RoundingMode;
43import java.nio.charset.Charset;
44import java.nio.charset.IllegalCharsetNameException;
45import java.nio.charset.UnsupportedCharsetException;
46import java.text.DateFormatSymbols;
47import java.text.DecimalFormat;
48import java.text.DecimalFormatSymbols;
49import java.text.NumberFormat;
50import java.util.regex.Matcher;
51import java.util.regex.Pattern;
52
53import java.time.DateTimeException;
54import java.time.Instant;
55import java.time.ZoneId;
56import java.time.ZoneOffset;
57import java.time.temporal.ChronoField;
58import java.time.temporal.TemporalAccessor;
59import java.time.temporal.TemporalQueries;
60import java.time.temporal.UnsupportedTemporalTypeException;
61
62import sun.misc.DoubleConsts;
63import sun.misc.FormattedFloatingDecimal;
64
65/**
66 * An interpreter for printf-style format strings.  This class provides support
67 * for layout justification and alignment, common formats for numeric, string,
68 * and date/time data, and locale-specific output.  Common Java types such as
69 * {@code byte}, {@link java.math.BigDecimal BigDecimal}, and {@link Calendar}
70 * are supported.  Limited formatting customization for arbitrary user types is
71 * provided through the {@link Formattable} interface.
72 *
73 * <p> Formatters are not necessarily safe for multithreaded access.  Thread
74 * safety is optional and is the responsibility of users of methods in this
75 * class.
76 *
77 * <p> Formatted printing for the Java language is heavily inspired by C's
78 * {@code printf}.  Although the format strings are similar to C, some
79 * customizations have been made to accommodate the Java language and exploit
80 * some of its features.  Also, Java formatting is more strict than C's; for
81 * example, if a conversion is incompatible with a flag, an exception will be
82 * thrown.  In C inapplicable flags are silently ignored.  The format strings
83 * are thus intended to be recognizable to C programmers but not necessarily
84 * completely compatible with those in C.
85 *
86 * <p> Examples of expected usage:
87 *
88 * <blockquote><pre>
89 *   StringBuilder sb = new StringBuilder();
90 *   // Send all output to the Appendable object sb
91 *   Formatter formatter = new Formatter(sb, Locale.US);
92 *
93 *   // Explicit argument indices may be used to re-order output.
94 *   formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
95 *   // -&gt; " d  c  b  a"
96 *
97 *   // Optional locale as the first argument can be used to get
98 *   // locale-specific formatting of numbers.  The precision and width can be
99 *   // given to round and align the value.
100 *   formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
101 *   // -&gt; "e =    +2,7183"
102 *
103 *   // The '(' numeric flag may be used to format negative numbers with
104 *   // parentheses rather than a minus sign.  Group separators are
105 *   // automatically inserted.
106 *   formatter.format("Amount gained or lost since last statement: $ %(,.2f",
107 *                    balanceDelta);
108 *   // -&gt; "Amount gained or lost since last statement: $ (6,217.58)"
109 * </pre></blockquote>
110 *
111 * <p> Convenience methods for common formatting requests exist as illustrated
112 * by the following invocations:
113 *
114 * <blockquote><pre>
115 *   // Writes a formatted string to System.out.
116 *   System.out.format("Local time: %tT", Calendar.getInstance());
117 *   // -&gt; "Local time: 13:34:18"
118 *
119 *   // Writes formatted output to System.err.
120 *   System.err.printf("Unable to open file '%1$s': %2$s",
121 *                     fileName, exception.getMessage());
122 *   // -&gt; "Unable to open file 'food': No such file or directory"
123 * </pre></blockquote>
124 *
125 * <p> Like C's {@code sprintf(3)}, Strings may be formatted using the static
126 * method {@link String#format(String,Object...) String.format}:
127 *
128 * <blockquote><pre>
129 *   // Format a string containing a date.
130 *   import java.util.Calendar;
131 *   import java.util.GregorianCalendar;
132 *   import static java.util.Calendar.*;
133 *
134 *   Calendar c = new GregorianCalendar(1995, MAY, 23);
135 *   String s = String.format("Duke's Birthday: %1$tb %1$te, %1$tY", c);
136 *   // -&gt; s == "Duke's Birthday: May 23, 1995"
137 * </pre></blockquote>
138 *
139 * <h3><a name="org">Organization</a></h3>
140 *
141 * <p> This specification is divided into two sections.  The first section, <a
142 * href="#summary">Summary</a>, covers the basic formatting concepts.  This
143 * section is intended for users who want to get started quickly and are
144 * familiar with formatted printing in other programming languages.  The second
145 * section, <a href="#detail">Details</a>, covers the specific implementation
146 * details.  It is intended for users who want more precise specification of
147 * formatting behavior.
148 *
149 * <h3><a name="summary">Summary</a></h3>
150 *
151 * <p> This section is intended to provide a brief overview of formatting
152 * concepts.  For precise behavioral details, refer to the <a
153 * href="#detail">Details</a> section.
154 *
155 * <h4><a name="syntax">Format String Syntax</a></h4>
156 *
157 * <p> Every method which produces formatted output requires a <i>format
158 * string</i> and an <i>argument list</i>.  The format string is a {@link
159 * String} which may contain fixed text and one or more embedded <i>format
160 * specifiers</i>.  Consider the following example:
161 *
162 * <blockquote><pre>
163 *   Calendar c = ...;
164 *   String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
165 * </pre></blockquote>
166 *
167 * This format string is the first argument to the {@code format} method.  It
168 * contains three format specifiers "{@code %1$tm}", "{@code %1$te}", and
169 * "{@code %1$tY}" which indicate how the arguments should be processed and
170 * where they should be inserted in the text.  The remaining portions of the
171 * format string are fixed text including {@code "Dukes Birthday: "} and any
172 * other spaces or punctuation.
173 *
174 * The argument list consists of all arguments passed to the method after the
175 * format string.  In the above example, the argument list is of size one and
176 * consists of the {@link java.util.Calendar Calendar} object {@code c}.
177 *
178 * <ul>
179 *
180 * <li> The format specifiers for general, character, and numeric types have
181 * the following syntax:
182 *
183 * <blockquote><pre>
184 *   %[argument_index$][flags][width][.precision]conversion
185 * </pre></blockquote>
186 *
187 * <p> The optional <i>argument_index</i> is a decimal integer indicating the
188 * position of the argument in the argument list.  The first argument is
189 * referenced by "{@code 1$}", the second by "{@code 2$}", etc.
190 *
191 * <p> The optional <i>flags</i> is a set of characters that modify the output
192 * format.  The set of valid flags depends on the conversion.
193 *
194 * <p> The optional <i>width</i> is a positive decimal integer indicating
195 * the minimum number of characters to be written to the output.
196 *
197 * <p> The optional <i>precision</i> is a non-negative decimal integer usually
198 * used to restrict the number of characters.  The specific behavior depends on
199 * the conversion.
200 *
201 * <p> The required <i>conversion</i> is a character indicating how the
202 * argument should be formatted.  The set of valid conversions for a given
203 * argument depends on the argument's data type.
204 *
205 * <li> The format specifiers for types which are used to represents dates and
206 * times have the following syntax:
207 *
208 * <blockquote><pre>
209 *   %[argument_index$][flags][width]conversion
210 * </pre></blockquote>
211 *
212 * <p> The optional <i>argument_index</i>, <i>flags</i> and <i>width</i> are
213 * defined as above.
214 *
215 * <p> The required <i>conversion</i> is a two character sequence.  The first
216 * character is {@code 't'} or {@code 'T'}.  The second character indicates
217 * the format to be used.  These characters are similar to but not completely
218 * identical to those defined by GNU {@code date} and POSIX
219 * {@code strftime(3c)}.
220 *
221 * <li> The format specifiers which do not correspond to arguments have the
222 * following syntax:
223 *
224 * <blockquote><pre>
225 *   %[flags][width]conversion
226 * </pre></blockquote>
227 *
228 * <p> The optional <i>flags</i> and <i>width</i> is defined as above.
229 *
230 * <p> The required <i>conversion</i> is a character indicating content to be
231 * inserted in the output.
232 *
233 * </ul>
234 *
235 * <h4> Conversions </h4>
236 *
237 * <p> Conversions are divided into the following categories:
238 *
239 * <ol>
240 *
241 * <li> <b>General</b> - may be applied to any argument
242 * type
243 *
244 * <li> <b>Character</b> - may be applied to basic types which represent
245 * Unicode characters: {@code char}, {@link Character}, {@code byte}, {@link
246 * Byte}, {@code short}, and {@link Short}. This conversion may also be
247 * applied to the types {@code int} and {@link Integer} when {@link
248 * Character#isValidCodePoint} returns {@code true}
249 *
250 * <li> <b>Numeric</b>
251 *
252 * <ol>
253 *
254 * <li> <b>Integral</b> - may be applied to Java integral types: {@code byte},
255 * {@link Byte}, {@code short}, {@link Short}, {@code int} and {@link
256 * Integer}, {@code long}, {@link Long}, and {@link java.math.BigInteger
257 * BigInteger} (but not {@code char} or {@link Character})
258 *
259 * <li><b>Floating Point</b> - may be applied to Java floating-point types:
260 * {@code float}, {@link Float}, {@code double}, {@link Double}, and {@link
261 * java.math.BigDecimal BigDecimal}
262 *
263 * </ol>
264 *
265 * <li> <b>Date/Time</b> - may be applied to Java types which are capable of
266 * encoding a date or time: {@code long}, {@link Long}, {@link Calendar},
267 * {@link Date} and {@link TemporalAccessor TemporalAccessor}
268 *
269 * <li> <b>Percent</b> - produces a literal {@code '%'}
270 * (<tt>'&#92;u0025'</tt>)
271 *
272 * <li> <b>Line Separator</b> - produces the platform-specific line separator
273 *
274 * </ol>
275 *
276 * <p> The following table summarizes the supported conversions.  Conversions
277 * denoted by an upper-case character (i.e. {@code 'B'}, {@code 'H'},
278 * {@code 'S'}, {@code 'C'}, {@code 'X'}, {@code 'E'}, {@code 'G'},
279 * {@code 'A'}, and {@code 'T'}) are the same as those for the corresponding
280 * lower-case conversion characters except that the result is converted to
281 * upper case according to the rules of the prevailing {@link java.util.Locale
282 * Locale}.  The result is equivalent to the following invocation of {@link
283 * String#toUpperCase()}
284 *
285 * <pre>
286 *    out.toUpperCase() </pre>
287 *
288 * <table cellpadding=5 summary="genConv">
289 *
290 * <tr><th valign="bottom"> Conversion
291 *     <th valign="bottom"> Argument Category
292 *     <th valign="bottom"> Description
293 *
294 * <tr><td valign="top"> {@code 'b'}, {@code 'B'}
295 *     <td valign="top"> general
296 *     <td> If the argument <i>arg</i> is {@code null}, then the result is
297 *     "{@code false}".  If <i>arg</i> is a {@code boolean} or {@link
298 *     Boolean}, then the result is the string returned by {@link
299 *     String#valueOf(boolean) String.valueOf(arg)}.  Otherwise, the result is
300 *     "true".
301 *
302 * <tr><td valign="top"> {@code 'h'}, {@code 'H'}
303 *     <td valign="top"> general
304 *     <td> If the argument <i>arg</i> is {@code null}, then the result is
305 *     "{@code null}".  Otherwise, the result is obtained by invoking
306 *     {@code Integer.toHexString(arg.hashCode())}.
307 *
308 * <tr><td valign="top"> {@code 's'}, {@code 'S'}
309 *     <td valign="top"> general
310 *     <td> If the argument <i>arg</i> is {@code null}, then the result is
311 *     "{@code null}".  If <i>arg</i> implements {@link Formattable}, then
312 *     {@link Formattable#formatTo arg.formatTo} is invoked. Otherwise, the
313 *     result is obtained by invoking {@code arg.toString()}.
314 *
315 * <tr><td valign="top">{@code 'c'}, {@code 'C'}
316 *     <td valign="top"> character
317 *     <td> The result is a Unicode character
318 *
319 * <tr><td valign="top">{@code 'd'}
320 *     <td valign="top"> integral
321 *     <td> The result is formatted as a decimal integer
322 *
323 * <tr><td valign="top">{@code 'o'}
324 *     <td valign="top"> integral
325 *     <td> The result is formatted as an octal integer
326 *
327 * <tr><td valign="top">{@code 'x'}, {@code 'X'}
328 *     <td valign="top"> integral
329 *     <td> The result is formatted as a hexadecimal integer
330 *
331 * <tr><td valign="top">{@code 'e'}, {@code 'E'}
332 *     <td valign="top"> floating point
333 *     <td> The result is formatted as a decimal number in computerized
334 *     scientific notation
335 *
336 * <tr><td valign="top">{@code 'f'}
337 *     <td valign="top"> floating point
338 *     <td> The result is formatted as a decimal number
339 *
340 * <tr><td valign="top">{@code 'g'}, {@code 'G'}
341 *     <td valign="top"> floating point
342 *     <td> The result is formatted using computerized scientific notation or
343 *     decimal format, depending on the precision and the value after rounding.
344 *
345 * <tr><td valign="top">{@code 'a'}, {@code 'A'}
346 *     <td valign="top"> floating point
347 *     <td> The result is formatted as a hexadecimal floating-point number with
348 *     a significand and an exponent. This conversion is <b>not</b> supported
349 *     for the {@code BigDecimal} type despite the latter's being in the
350 *     <i>floating point</i> argument category.
351 *
352 * <tr><td valign="top">{@code 't'}, {@code 'T'}
353 *     <td valign="top"> date/time
354 *     <td> Prefix for date and time conversion characters.  See <a
355 *     href="#dt">Date/Time Conversions</a>.
356 *
357 * <tr><td valign="top">{@code '%'}
358 *     <td valign="top"> percent
359 *     <td> The result is a literal {@code '%'} (<tt>'&#92;u0025'</tt>)
360 *
361 * <tr><td valign="top">{@code 'n'}
362 *     <td valign="top"> line separator
363 *     <td> The result is the platform-specific line separator
364 *
365 * </table>
366 *
367 * <p> Any characters not explicitly defined as conversions are illegal and are
368 * reserved for future extensions.
369 *
370 * <h4><a name="dt">Date/Time Conversions</a></h4>
371 *
372 * <p> The following date and time conversion suffix characters are defined for
373 * the {@code 't'} and {@code 'T'} conversions.  The types are similar to but
374 * not completely identical to those defined by GNU {@code date} and POSIX
375 * {@code strftime(3c)}.  Additional conversion types are provided to access
376 * Java-specific functionality (e.g. {@code 'L'} for milliseconds within the
377 * second).
378 *
379 * <p> The following conversion characters are used for formatting times:
380 *
381 * <table cellpadding=5 summary="time">
382 *
383 * <tr><td valign="top"> {@code 'H'}
384 *     <td> Hour of the day for the 24-hour clock, formatted as two digits with
385 *     a leading zero as necessary i.e. {@code 00 - 23}.
386 *
387 * <tr><td valign="top">{@code 'I'}
388 *     <td> Hour for the 12-hour clock, formatted as two digits with a leading
389 *     zero as necessary, i.e.  {@code 01 - 12}.
390 *
391 * <tr><td valign="top">{@code 'k'}
392 *     <td> Hour of the day for the 24-hour clock, i.e. {@code 0 - 23}.
393 *
394 * <tr><td valign="top">{@code 'l'}
395 *     <td> Hour for the 12-hour clock, i.e. {@code 1 - 12}.
396 *
397 * <tr><td valign="top">{@code 'M'}
398 *     <td> Minute within the hour formatted as two digits with a leading zero
399 *     as necessary, i.e.  {@code 00 - 59}.
400 *
401 * <tr><td valign="top">{@code 'S'}
402 *     <td> Seconds within the minute, formatted as two digits with a leading
403 *     zero as necessary, i.e. {@code 00 - 60} ("{@code 60}" is a special
404 *     value required to support leap seconds).
405 *
406 * <tr><td valign="top">{@code 'L'}
407 *     <td> Millisecond within the second formatted as three digits with
408 *     leading zeros as necessary, i.e. {@code 000 - 999}.
409 *
410 * <tr><td valign="top">{@code 'N'}
411 *     <td> Nanosecond within the second, formatted as nine digits with leading
412 *     zeros as necessary, i.e. {@code 000000000 - 999999999}.
413 *
414 * <tr><td valign="top">{@code 'p'}
415 *     <td> Locale-specific {@linkplain
416 *     java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker
417 *     in lower case, e.g."{@code am}" or "{@code pm}". Use of the conversion
418 *     prefix {@code 'T'} forces this output to upper case.
419 *
420 * <tr><td valign="top">{@code 'z'}
421 *     <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC&nbsp;822</a>
422 *     style numeric time zone offset from GMT, e.g. {@code -0800}.  This
423 *     value will be adjusted as necessary for Daylight Saving Time.  For
424 *     {@code long}, {@link Long}, and {@link Date} the time zone used is
425 *     the {@linkplain TimeZone#getDefault() default time zone} for this
426 *     instance of the Java virtual machine.
427 *
428 * <tr><td valign="top">{@code 'Z'}
429 *     <td> A string representing the abbreviation for the time zone.  This
430 *     value will be adjusted as necessary for Daylight Saving Time.  For
431 *     {@code long}, {@link Long}, and {@link Date} the  time zone used is
432 *     the {@linkplain TimeZone#getDefault() default time zone} for this
433 *     instance of the Java virtual machine.  The Formatter's locale will
434 *     supersede the locale of the argument (if any).
435 *
436 * <tr><td valign="top">{@code 's'}
437 *     <td> Seconds since the beginning of the epoch starting at 1 January 1970
438 *     {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE/1000} to
439 *     {@code Long.MAX_VALUE/1000}.
440 *
441 * <tr><td valign="top">{@code 'Q'}
442 *     <td> Milliseconds since the beginning of the epoch starting at 1 January
443 *     1970 {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE} to
444 *     {@code Long.MAX_VALUE}.
445 *
446 * </table>
447 *
448 * <p> The following conversion characters are used for formatting dates:
449 *
450 * <table cellpadding=5 summary="date">
451 *
452 * <tr><td valign="top">{@code 'B'}
453 *     <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths
454 *     full month name}, e.g. {@code "January"}, {@code "February"}.
455 *
456 * <tr><td valign="top">{@code 'b'}
457 *     <td> Locale-specific {@linkplain
458 *     java.text.DateFormatSymbols#getShortMonths abbreviated month name},
459 *     e.g. {@code "Jan"}, {@code "Feb"}.
460 *
461 * <tr><td valign="top">{@code 'h'}
462 *     <td> Same as {@code 'b'}.
463 *
464 * <tr><td valign="top">{@code 'A'}
465 *     <td> Locale-specific full name of the {@linkplain
466 *     java.text.DateFormatSymbols#getWeekdays day of the week},
467 *     e.g. {@code "Sunday"}, {@code "Monday"}
468 *
469 * <tr><td valign="top">{@code 'a'}
470 *     <td> Locale-specific short name of the {@linkplain
471 *     java.text.DateFormatSymbols#getShortWeekdays day of the week},
472 *     e.g. {@code "Sun"}, {@code "Mon"}
473 *
474 * <tr><td valign="top">{@code 'C'}
475 *     <td> Four-digit year divided by {@code 100}, formatted as two digits
476 *     with leading zero as necessary, i.e. {@code 00 - 99}
477 *
478 * <tr><td valign="top">{@code 'Y'}
479 *     <td> Year, formatted as at least four digits with leading zeros as
480 *     necessary, e.g. {@code 0092} equals {@code 92} CE for the Gregorian
481 *     calendar.
482 *
483 * <tr><td valign="top">{@code 'y'}
484 *     <td> Last two digits of the year, formatted with leading zeros as
485 *     necessary, i.e. {@code 00 - 99}.
486 *
487 * <tr><td valign="top">{@code 'j'}
488 *     <td> Day of year, formatted as three digits with leading zeros as
489 *     necessary, e.g. {@code 001 - 366} for the Gregorian calendar.
490 *
491 * <tr><td valign="top">{@code 'm'}
492 *     <td> Month, formatted as two digits with leading zeros as necessary,
493 *     i.e. {@code 01 - 13}.
494 *
495 * <tr><td valign="top">{@code 'd'}
496 *     <td> Day of month, formatted as two digits with leading zeros as
497 *     necessary, i.e. {@code 01 - 31}
498 *
499 * <tr><td valign="top">{@code 'e'}
500 *     <td> Day of month, formatted as two digits, i.e. {@code 1 - 31}.
501 *
502 * </table>
503 *
504 * <p> The following conversion characters are used for formatting common
505 * date/time compositions.
506 *
507 * <table cellpadding=5 summary="composites">
508 *
509 * <tr><td valign="top">{@code 'R'}
510 *     <td> Time formatted for the 24-hour clock as {@code "%tH:%tM"}
511 *
512 * <tr><td valign="top">{@code 'T'}
513 *     <td> Time formatted for the 24-hour clock as {@code "%tH:%tM:%tS"}.
514 *
515 * <tr><td valign="top">{@code 'r'}
516 *     <td> Time formatted for the 12-hour clock as {@code "%tI:%tM:%tS %Tp"}.
517 *     The location of the morning or afternoon marker ({@code '%Tp'}) may be
518 *     locale-dependent.
519 *
520 * <tr><td valign="top">{@code 'D'}
521 *     <td> Date formatted as {@code "%tm/%td/%ty"}.
522 *
523 * <tr><td valign="top">{@code 'F'}
524 *     <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO&nbsp;8601</a>
525 *     complete date formatted as {@code "%tY-%tm-%td"}.
526 *
527 * <tr><td valign="top">{@code 'c'}
528 *     <td> Date and time formatted as {@code "%ta %tb %td %tT %tZ %tY"},
529 *     e.g. {@code "Sun Jul 20 16:17:00 EDT 1969"}.
530 *
531 * </table>
532 *
533 * <p> Any characters not explicitly defined as date/time conversion suffixes
534 * are illegal and are reserved for future extensions.
535 *
536 * <h4> Flags </h4>
537 *
538 * <p> The following table summarizes the supported flags.  <i>y</i> means the
539 * flag is supported for the indicated argument types.
540 *
541 * <table cellpadding=5 summary="genConv">
542 *
543 * <tr><th valign="bottom"> Flag <th valign="bottom"> General
544 *     <th valign="bottom"> Character <th valign="bottom"> Integral
545 *     <th valign="bottom"> Floating Point
546 *     <th valign="bottom"> Date/Time
547 *     <th valign="bottom"> Description
548 *
549 * <tr><td> '-' <td align="center" valign="top"> y
550 *     <td align="center" valign="top"> y
551 *     <td align="center" valign="top"> y
552 *     <td align="center" valign="top"> y
553 *     <td align="center" valign="top"> y
554 *     <td> The result will be left-justified.
555 *
556 * <tr><td> '#' <td align="center" valign="top"> y<sup>1</sup>
557 *     <td align="center" valign="top"> -
558 *     <td align="center" valign="top"> y<sup>3</sup>
559 *     <td align="center" valign="top"> y
560 *     <td align="center" valign="top"> -
561 *     <td> The result should use a conversion-dependent alternate form
562 *
563 * <tr><td> '+' <td align="center" valign="top"> -
564 *     <td align="center" valign="top"> -
565 *     <td align="center" valign="top"> y<sup>4</sup>
566 *     <td align="center" valign="top"> y
567 *     <td align="center" valign="top"> -
568 *     <td> The result will always include a sign
569 *
570 * <tr><td> '&nbsp;&nbsp;' <td align="center" valign="top"> -
571 *     <td align="center" valign="top"> -
572 *     <td align="center" valign="top"> y<sup>4</sup>
573 *     <td align="center" valign="top"> y
574 *     <td align="center" valign="top"> -
575 *     <td> The result will include a leading space for positive values
576 *
577 * <tr><td> '0' <td align="center" valign="top"> -
578 *     <td align="center" valign="top"> -
579 *     <td align="center" valign="top"> y
580 *     <td align="center" valign="top"> y
581 *     <td align="center" valign="top"> -
582 *     <td> The result will be zero-padded
583 *
584 * <tr><td> ',' <td align="center" valign="top"> -
585 *     <td align="center" valign="top"> -
586 *     <td align="center" valign="top"> y<sup>2</sup>
587 *     <td align="center" valign="top"> y<sup>5</sup>
588 *     <td align="center" valign="top"> -
589 *     <td> The result will include locale-specific {@linkplain
590 *     java.text.DecimalFormatSymbols#getGroupingSeparator grouping separators}
591 *
592 * <tr><td> '(' <td align="center" valign="top"> -
593 *     <td align="center" valign="top"> -
594 *     <td align="center" valign="top"> y<sup>4</sup>
595 *     <td align="center" valign="top"> y<sup>5</sup>
596 *     <td align="center"> -
597 *     <td> The result will enclose negative numbers in parentheses
598 *
599 * </table>
600 *
601 * <p> <sup>1</sup> Depends on the definition of {@link Formattable}.
602 *
603 * <p> <sup>2</sup> For {@code 'd'} conversion only.
604 *
605 * <p> <sup>3</sup> For {@code 'o'}, {@code 'x'}, and {@code 'X'}
606 * conversions only.
607 *
608 * <p> <sup>4</sup> For {@code 'd'}, {@code 'o'}, {@code 'x'}, and
609 * {@code 'X'} conversions applied to {@link java.math.BigInteger BigInteger}
610 * or {@code 'd'} applied to {@code byte}, {@link Byte}, {@code short}, {@link
611 * Short}, {@code int} and {@link Integer}, {@code long}, and {@link Long}.
612 *
613 * <p> <sup>5</sup> For {@code 'e'}, {@code 'E'}, {@code 'f'},
614 * {@code 'g'}, and {@code 'G'} conversions only.
615 *
616 * <p> Any characters not explicitly defined as flags are illegal and are
617 * reserved for future extensions.
618 *
619 * <h4> Width </h4>
620 *
621 * <p> The width is the minimum number of characters to be written to the
622 * output.  For the line separator conversion, width is not applicable; if it
623 * is provided, an exception will be thrown.
624 *
625 * <h4> Precision </h4>
626 *
627 * <p> For general argument types, the precision is the maximum number of
628 * characters to be written to the output.
629 *
630 * <p> For the floating-point conversions {@code 'a'}, {@code 'A'}, {@code 'e'},
631 * {@code 'E'}, and {@code 'f'} the precision is the number of digits after the
632 * radix point.  If the conversion is {@code 'g'} or {@code 'G'}, then the
633 * precision is the total number of digits in the resulting magnitude after
634 * rounding.
635 *
636 * <p> For character, integral, and date/time argument types and the percent
637 * and line separator conversions, the precision is not applicable; if a
638 * precision is provided, an exception will be thrown.
639 *
640 * <h4> Argument Index </h4>
641 *
642 * <p> The argument index is a decimal integer indicating the position of the
643 * argument in the argument list.  The first argument is referenced by
644 * "{@code 1$}", the second by "{@code 2$}", etc.
645 *
646 * <p> Another way to reference arguments by position is to use the
647 * {@code '<'} (<tt>'&#92;u003c'</tt>) flag, which causes the argument for
648 * the previous format specifier to be re-used.  For example, the following two
649 * statements would produce identical strings:
650 *
651 * <blockquote><pre>
652 *   Calendar c = ...;
653 *   String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
654 *
655 *   String s2 = String.format("Duke's Birthday: %1$tm %&lt;te,%&lt;tY", c);
656 * </pre></blockquote>
657 *
658 * <hr>
659 * <h3><a name="detail">Details</a></h3>
660 *
661 * <p> This section is intended to provide behavioral details for formatting,
662 * including conditions and exceptions, supported data types, localization, and
663 * interactions between flags, conversions, and data types.  For an overview of
664 * formatting concepts, refer to the <a href="#summary">Summary</a>
665 *
666 * <p> Any characters not explicitly defined as conversions, date/time
667 * conversion suffixes, or flags are illegal and are reserved for
668 * future extensions.  Use of such a character in a format string will
669 * cause an {@link UnknownFormatConversionException} or {@link
670 * UnknownFormatFlagsException} to be thrown.
671 *
672 * <p> If the format specifier contains a width or precision with an invalid
673 * value or which is otherwise unsupported, then a {@link
674 * IllegalFormatWidthException} or {@link IllegalFormatPrecisionException}
675 * respectively will be thrown.
676 *
677 * <p> If a format specifier contains a conversion character that is not
678 * applicable to the corresponding argument, then an {@link
679 * IllegalFormatConversionException} will be thrown.
680 *
681 * <p> All specified exceptions may be thrown by any of the {@code format}
682 * methods of {@code Formatter} as well as by any {@code format} convenience
683 * methods such as {@link String#format(String,Object...) String.format} and
684 * {@link java.io.PrintStream#printf(String,Object...) PrintStream.printf}.
685 *
686 * <p> Conversions denoted by an upper-case character (i.e. {@code 'B'},
687 * {@code 'H'}, {@code 'S'}, {@code 'C'}, {@code 'X'}, {@code 'E'},
688 * {@code 'G'}, {@code 'A'}, and {@code 'T'}) are the same as those for the
689 * corresponding lower-case conversion characters except that the result is
690 * converted to upper case according to the rules of the prevailing {@link
691 * java.util.Locale Locale}.  The result is equivalent to the following
692 * invocation of {@link String#toUpperCase()}
693 *
694 * <pre>
695 *    out.toUpperCase() </pre>
696 *
697 * <h4><a name="dgen">General</a></h4>
698 *
699 * <p> The following general conversions may be applied to any argument type:
700 *
701 * <table cellpadding=5 summary="dgConv">
702 *
703 * <tr><td valign="top"> {@code 'b'}
704 *     <td valign="top"> <tt>'&#92;u0062'</tt>
705 *     <td> Produces either "{@code true}" or "{@code false}" as returned by
706 *     {@link Boolean#toString(boolean)}.
707 *
708 *     <p> If the argument is {@code null}, then the result is
709 *     "{@code false}".  If the argument is a {@code boolean} or {@link
710 *     Boolean}, then the result is the string returned by {@link
711 *     String#valueOf(boolean) String.valueOf()}.  Otherwise, the result is
712 *     "{@code true}".
713 *
714 *     <p> If the {@code '#'} flag is given, then a {@link
715 *     FormatFlagsConversionMismatchException} will be thrown.
716 *
717 * <tr><td valign="top"> {@code 'B'}
718 *     <td valign="top"> <tt>'&#92;u0042'</tt>
719 *     <td> The upper-case variant of {@code 'b'}.
720 *
721 * <tr><td valign="top"> {@code 'h'}
722 *     <td valign="top"> <tt>'&#92;u0068'</tt>
723 *     <td> Produces a string representing the hash code value of the object.
724 *
725 *     <p> If the argument, <i>arg</i> is {@code null}, then the
726 *     result is "{@code null}".  Otherwise, the result is obtained
727 *     by invoking {@code Integer.toHexString(arg.hashCode())}.
728 *
729 *     <p> If the {@code '#'} flag is given, then a {@link
730 *     FormatFlagsConversionMismatchException} will be thrown.
731 *
732 * <tr><td valign="top"> {@code 'H'}
733 *     <td valign="top"> <tt>'&#92;u0048'</tt>
734 *     <td> The upper-case variant of {@code 'h'}.
735 *
736 * <tr><td valign="top"> {@code 's'}
737 *     <td valign="top"> <tt>'&#92;u0073'</tt>
738 *     <td> Produces a string.
739 *
740 *     <p> If the argument is {@code null}, then the result is
741 *     "{@code null}".  If the argument implements {@link Formattable}, then
742 *     its {@link Formattable#formatTo formatTo} method is invoked.
743 *     Otherwise, the result is obtained by invoking the argument's
744 *     {@code toString()} method.
745 *
746 *     <p> If the {@code '#'} flag is given and the argument is not a {@link
747 *     Formattable} , then a {@link FormatFlagsConversionMismatchException}
748 *     will be thrown.
749 *
750 * <tr><td valign="top"> {@code 'S'}
751 *     <td valign="top"> <tt>'&#92;u0053'</tt>
752 *     <td> The upper-case variant of {@code 's'}.
753 *
754 * </table>
755 *
756 * <p> The following <a name="dFlags">flags</a> apply to general conversions:
757 *
758 * <table cellpadding=5 summary="dFlags">
759 *
760 * <tr><td valign="top"> {@code '-'}
761 *     <td valign="top"> <tt>'&#92;u002d'</tt>
762 *     <td> Left justifies the output.  Spaces (<tt>'&#92;u0020'</tt>) will be
763 *     added at the end of the converted value as required to fill the minimum
764 *     width of the field.  If the width is not provided, then a {@link
765 *     MissingFormatWidthException} will be thrown.  If this flag is not given
766 *     then the output will be right-justified.
767 *
768 * <tr><td valign="top"> {@code '#'}
769 *     <td valign="top"> <tt>'&#92;u0023'</tt>
770 *     <td> Requires the output use an alternate form.  The definition of the
771 *     form is specified by the conversion.
772 *
773 * </table>
774 *
775 * <p> The <a name="genWidth">width</a> is the minimum number of characters to
776 * be written to the
777 * output.  If the length of the converted value is less than the width then
778 * the output will be padded by <tt>'&nbsp;&nbsp;'</tt> (<tt>'&#92;u0020'</tt>)
779 * until the total number of characters equals the width.  The padding is on
780 * the left by default.  If the {@code '-'} flag is given, then the padding
781 * will be on the right.  If the width is not specified then there is no
782 * minimum.
783 *
784 * <p> The precision is the maximum number of characters to be written to the
785 * output.  The precision is applied before the width, thus the output will be
786 * truncated to {@code precision} characters even if the width is greater than
787 * the precision.  If the precision is not specified then there is no explicit
788 * limit on the number of characters.
789 *
790 * <h4><a name="dchar">Character</a></h4>
791 *
792 * This conversion may be applied to {@code char} and {@link Character}.  It
793 * may also be applied to the types {@code byte}, {@link Byte},
794 * {@code short}, and {@link Short}, {@code int} and {@link Integer} when
795 * {@link Character#isValidCodePoint} returns {@code true}.  If it returns
796 * {@code false} then an {@link IllegalFormatCodePointException} will be
797 * thrown.
798 *
799 * <table cellpadding=5 summary="charConv">
800 *
801 * <tr><td valign="top"> {@code 'c'}
802 *     <td valign="top"> <tt>'&#92;u0063'</tt>
803 *     <td> Formats the argument as a Unicode character as described in <a
804 *     href="../lang/Character.html#unicode">Unicode Character
805 *     Representation</a>.  This may be more than one 16-bit {@code char} in
806 *     the case where the argument represents a supplementary character.
807 *
808 *     <p> If the {@code '#'} flag is given, then a {@link
809 *     FormatFlagsConversionMismatchException} will be thrown.
810 *
811 * <tr><td valign="top"> {@code 'C'}
812 *     <td valign="top"> <tt>'&#92;u0043'</tt>
813 *     <td> The upper-case variant of {@code 'c'}.
814 *
815 * </table>
816 *
817 * <p> The {@code '-'} flag defined for <a href="#dFlags">General
818 * conversions</a> applies.  If the {@code '#'} flag is given, then a {@link
819 * FormatFlagsConversionMismatchException} will be thrown.
820 *
821 * <p> The width is defined as for <a href="#genWidth">General conversions</a>.
822 *
823 * <p> The precision is not applicable.  If the precision is specified then an
824 * {@link IllegalFormatPrecisionException} will be thrown.
825 *
826 * <h4><a name="dnum">Numeric</a></h4>
827 *
828 * <p> Numeric conversions are divided into the following categories:
829 *
830 * <ol>
831 *
832 * <li> <a href="#dnint"><b>Byte, Short, Integer, and Long</b></a>
833 *
834 * <li> <a href="#dnbint"><b>BigInteger</b></a>
835 *
836 * <li> <a href="#dndec"><b>Float and Double</b></a>
837 *
838 * <li> <a href="#dnbdec"><b>BigDecimal</b></a>
839 *
840 * </ol>
841 *
842 * <p> Numeric types will be formatted according to the following algorithm:
843 *
844 * <p><b><a name="L10nAlgorithm"> Number Localization Algorithm</a></b>
845 *
846 * <p> After digits are obtained for the integer part, fractional part, and
847 * exponent (as appropriate for the data type), the following transformation
848 * is applied:
849 *
850 * <ol>
851 *
852 * <li> Each digit character <i>d</i> in the string is replaced by a
853 * locale-specific digit computed relative to the current locale's
854 * {@linkplain java.text.DecimalFormatSymbols#getZeroDigit() zero digit}
855 * <i>z</i>; that is <i>d&nbsp;-&nbsp;</i> {@code '0'}
856 * <i>&nbsp;+&nbsp;z</i>.
857 *
858 * <li> If a decimal separator is present, a locale-specific {@linkplain
859 * java.text.DecimalFormatSymbols#getDecimalSeparator decimal separator} is
860 * substituted.
861 *
862 * <li> If the {@code ','} (<tt>'&#92;u002c'</tt>)
863 * <a name="L10nGroup">flag</a> is given, then the locale-specific {@linkplain
864 * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is
865 * inserted by scanning the integer part of the string from least significant
866 * to most significant digits and inserting a separator at intervals defined by
867 * the locale's {@linkplain java.text.DecimalFormat#getGroupingSize() grouping
868 * size}.
869 *
870 * <li> If the {@code '0'} flag is given, then the locale-specific {@linkplain
871 * java.text.DecimalFormatSymbols#getZeroDigit() zero digits} are inserted
872 * after the sign character, if any, and before the first non-zero digit, until
873 * the length of the string is equal to the requested field width.
874 *
875 * <li> If the value is negative and the {@code '('} flag is given, then a
876 * {@code '('} (<tt>'&#92;u0028'</tt>) is prepended and a {@code ')'}
877 * (<tt>'&#92;u0029'</tt>) is appended.
878 *
879 * <li> If the value is negative (or floating-point negative zero) and
880 * {@code '('} flag is not given, then a {@code '-'} (<tt>'&#92;u002d'</tt>)
881 * is prepended.
882 *
883 * <li> If the {@code '+'} flag is given and the value is positive or zero (or
884 * floating-point positive zero), then a {@code '+'} (<tt>'&#92;u002b'</tt>)
885 * will be prepended.
886 *
887 * </ol>
888 *
889 * <p> If the value is NaN or positive infinity the literal strings "NaN" or
890 * "Infinity" respectively, will be output.  If the value is negative infinity,
891 * then the output will be "(Infinity)" if the {@code '('} flag is given
892 * otherwise the output will be "-Infinity".  These values are not localized.
893 *
894 * <p><a name="dnint"><b> Byte, Short, Integer, and Long </b></a>
895 *
896 * <p> The following conversions may be applied to {@code byte}, {@link Byte},
897 * {@code short}, {@link Short}, {@code int} and {@link Integer},
898 * {@code long}, and {@link Long}.
899 *
900 * <table cellpadding=5 summary="IntConv">
901 *
902 * <tr><td valign="top"> {@code 'd'}
903 *     <td valign="top"> <tt>'&#92;u0064'</tt>
904 *     <td> Formats the argument as a decimal integer. The <a
905 *     href="#L10nAlgorithm">localization algorithm</a> is applied.
906 *
907 *     <p> If the {@code '0'} flag is given and the value is negative, then
908 *     the zero padding will occur after the sign.
909 *
910 *     <p> If the {@code '#'} flag is given then a {@link
911 *     FormatFlagsConversionMismatchException} will be thrown.
912 *
913 * <tr><td valign="top"> {@code 'o'}
914 *     <td valign="top"> <tt>'&#92;u006f'</tt>
915 *     <td> Formats the argument as an integer in base eight.  No localization
916 *     is applied.
917 *
918 *     <p> If <i>x</i> is negative then the result will be an unsigned value
919 *     generated by adding 2<sup>n</sup> to the value where {@code n} is the
920 *     number of bits in the type as returned by the static {@code SIZE} field
921 *     in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short},
922 *     {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long}
923 *     classes as appropriate.
924 *
925 *     <p> If the {@code '#'} flag is given then the output will always begin
926 *     with the radix indicator {@code '0'}.
927 *
928 *     <p> If the {@code '0'} flag is given then the output will be padded
929 *     with leading zeros to the field width following any indication of sign.
930 *
931 *     <p> If {@code '('}, {@code '+'}, '&nbsp;&nbsp;', or {@code ','} flags
932 *     are given then a {@link FormatFlagsConversionMismatchException} will be
933 *     thrown.
934 *
935 * <tr><td valign="top"> {@code 'x'}
936 *     <td valign="top"> <tt>'&#92;u0078'</tt>
937 *     <td> Formats the argument as an integer in base sixteen. No
938 *     localization is applied.
939 *
940 *     <p> If <i>x</i> is negative then the result will be an unsigned value
941 *     generated by adding 2<sup>n</sup> to the value where {@code n} is the
942 *     number of bits in the type as returned by the static {@code SIZE} field
943 *     in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short},
944 *     {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long}
945 *     classes as appropriate.
946 *
947 *     <p> If the {@code '#'} flag is given then the output will always begin
948 *     with the radix indicator {@code "0x"}.
949 *
950 *     <p> If the {@code '0'} flag is given then the output will be padded to
951 *     the field width with leading zeros after the radix indicator or sign (if
952 *     present).
953 *
954 *     <p> If {@code '('}, <tt>'&nbsp;&nbsp;'</tt>, {@code '+'}, or
955 *     {@code ','} flags are given then a {@link
956 *     FormatFlagsConversionMismatchException} will be thrown.
957 *
958 * <tr><td valign="top"> {@code 'X'}
959 *     <td valign="top"> <tt>'&#92;u0058'</tt>
960 *     <td> The upper-case variant of {@code 'x'}.  The entire string
961 *     representing the number will be converted to {@linkplain
962 *     String#toUpperCase upper case} including the {@code 'x'} (if any) and
963 *     all hexadecimal digits {@code 'a'} - {@code 'f'}
964 *     (<tt>'&#92;u0061'</tt> -  <tt>'&#92;u0066'</tt>).
965 *
966 * </table>
967 *
968 * <p> If the conversion is {@code 'o'}, {@code 'x'}, or {@code 'X'} and
969 * both the {@code '#'} and the {@code '0'} flags are given, then result will
970 * contain the radix indicator ({@code '0'} for octal and {@code "0x"} or
971 * {@code "0X"} for hexadecimal), some number of zeros (based on the width),
972 * and the value.
973 *
974 * <p> If the {@code '-'} flag is not given, then the space padding will occur
975 * before the sign.
976 *
977 * <p> The following <a name="intFlags">flags</a> apply to numeric integral
978 * conversions:
979 *
980 * <table cellpadding=5 summary="intFlags">
981 *
982 * <tr><td valign="top"> {@code '+'}
983 *     <td valign="top"> <tt>'&#92;u002b'</tt>
984 *     <td> Requires the output to include a positive sign for all positive
985 *     numbers.  If this flag is not given then only negative values will
986 *     include a sign.
987 *
988 *     <p> If both the {@code '+'} and <tt>'&nbsp;&nbsp;'</tt> flags are given
989 *     then an {@link IllegalFormatFlagsException} will be thrown.
990 *
991 * <tr><td valign="top"> <tt>'&nbsp;&nbsp;'</tt>
992 *     <td valign="top"> <tt>'&#92;u0020'</tt>
993 *     <td> Requires the output to include a single extra space
994 *     (<tt>'&#92;u0020'</tt>) for non-negative values.
995 *
996 *     <p> If both the {@code '+'} and <tt>'&nbsp;&nbsp;'</tt> flags are given
997 *     then an {@link IllegalFormatFlagsException} will be thrown.
998 *
999 * <tr><td valign="top"> {@code '0'}
1000 *     <td valign="top"> <tt>'&#92;u0030'</tt>
1001 *     <td> Requires the output to be padded with leading {@linkplain
1002 *     java.text.DecimalFormatSymbols#getZeroDigit zeros} to the minimum field
1003 *     width following any sign or radix indicator except when converting NaN
1004 *     or infinity.  If the width is not provided, then a {@link
1005 *     MissingFormatWidthException} will be thrown.
1006 *
1007 *     <p> If both the {@code '-'} and {@code '0'} flags are given then an
1008 *     {@link IllegalFormatFlagsException} will be thrown.
1009 *
1010 * <tr><td valign="top"> {@code ','}
1011 *     <td valign="top"> <tt>'&#92;u002c'</tt>
1012 *     <td> Requires the output to include the locale-specific {@linkplain
1013 *     java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as
1014 *     described in the <a href="#L10nGroup">"group" section</a> of the
1015 *     localization algorithm.
1016 *
1017 * <tr><td valign="top"> {@code '('}
1018 *     <td valign="top"> <tt>'&#92;u0028'</tt>
1019 *     <td> Requires the output to prepend a {@code '('}
1020 *     (<tt>'&#92;u0028'</tt>) and append a {@code ')'}
1021 *     (<tt>'&#92;u0029'</tt>) to negative values.
1022 *
1023 * </table>
1024 *
1025 * <p> If no <a name="intdFlags">flags</a> are given the default formatting is
1026 * as follows:
1027 *
1028 * <ul>
1029 *
1030 * <li> The output is right-justified within the {@code width}
1031 *
1032 * <li> Negative numbers begin with a {@code '-'} (<tt>'&#92;u002d'</tt>)
1033 *
1034 * <li> Positive numbers and zero do not include a sign or extra leading
1035 * space
1036 *
1037 * <li> No grouping separators are included
1038 *
1039 * </ul>
1040 *
1041 * <p> The <a name="intWidth">width</a> is the minimum number of characters to
1042 * be written to the output.  This includes any signs, digits, grouping
1043 * separators, radix indicator, and parentheses.  If the length of the
1044 * converted value is less than the width then the output will be padded by
1045 * spaces (<tt>'&#92;u0020'</tt>) until the total number of characters equals
1046 * width.  The padding is on the left by default.  If {@code '-'} flag is
1047 * given then the padding will be on the right.  If width is not specified then
1048 * there is no minimum.
1049 *
1050 * <p> The precision is not applicable.  If precision is specified then an
1051 * {@link IllegalFormatPrecisionException} will be thrown.
1052 *
1053 * <p><a name="dnbint"><b> BigInteger </b></a>
1054 *
1055 * <p> The following conversions may be applied to {@link
1056 * java.math.BigInteger}.
1057 *
1058 * <table cellpadding=5 summary="BIntConv">
1059 *
1060 * <tr><td valign="top"> {@code 'd'}
1061 *     <td valign="top"> <tt>'&#92;u0064'</tt>
1062 *     <td> Requires the output to be formatted as a decimal integer. The <a
1063 *     href="#L10nAlgorithm">localization algorithm</a> is applied.
1064 *
1065 *     <p> If the {@code '#'} flag is given {@link
1066 *     FormatFlagsConversionMismatchException} will be thrown.
1067 *
1068 * <tr><td valign="top"> {@code 'o'}
1069 *     <td valign="top"> <tt>'&#92;u006f'</tt>
1070 *     <td> Requires the output to be formatted as an integer in base eight.
1071 *     No localization is applied.
1072 *
1073 *     <p> If <i>x</i> is negative then the result will be a signed value
1074 *     beginning with {@code '-'} (<tt>'&#92;u002d'</tt>).  Signed output is
1075 *     allowed for this type because unlike the primitive types it is not
1076 *     possible to create an unsigned equivalent without assuming an explicit
1077 *     data-type size.
1078 *
1079 *     <p> If <i>x</i> is positive or zero and the {@code '+'} flag is given
1080 *     then the result will begin with {@code '+'} (<tt>'&#92;u002b'</tt>).
1081 *
1082 *     <p> If the {@code '#'} flag is given then the output will always begin
1083 *     with {@code '0'} prefix.
1084 *
1085 *     <p> If the {@code '0'} flag is given then the output will be padded
1086 *     with leading zeros to the field width following any indication of sign.
1087 *
1088 *     <p> If the {@code ','} flag is given then a {@link
1089 *     FormatFlagsConversionMismatchException} will be thrown.
1090 *
1091 * <tr><td valign="top"> {@code 'x'}
1092 *     <td valign="top"> <tt>'&#92;u0078'</tt>
1093 *     <td> Requires the output to be formatted as an integer in base
1094 *     sixteen.  No localization is applied.
1095 *
1096 *     <p> If <i>x</i> is negative then the result will be a signed value
1097 *     beginning with {@code '-'} (<tt>'&#92;u002d'</tt>).  Signed output is
1098 *     allowed for this type because unlike the primitive types it is not
1099 *     possible to create an unsigned equivalent without assuming an explicit
1100 *     data-type size.
1101 *
1102 *     <p> If <i>x</i> is positive or zero and the {@code '+'} flag is given
1103 *     then the result will begin with {@code '+'} (<tt>'&#92;u002b'</tt>).
1104 *
1105 *     <p> If the {@code '#'} flag is given then the output will always begin
1106 *     with the radix indicator {@code "0x"}.
1107 *
1108 *     <p> If the {@code '0'} flag is given then the output will be padded to
1109 *     the field width with leading zeros after the radix indicator or sign (if
1110 *     present).
1111 *
1112 *     <p> If the {@code ','} flag is given then a {@link
1113 *     FormatFlagsConversionMismatchException} will be thrown.
1114 *
1115 * <tr><td valign="top"> {@code 'X'}
1116 *     <td valign="top"> <tt>'&#92;u0058'</tt>
1117 *     <td> The upper-case variant of {@code 'x'}.  The entire string
1118 *     representing the number will be converted to {@linkplain
1119 *     String#toUpperCase upper case} including the {@code 'x'} (if any) and
1120 *     all hexadecimal digits {@code 'a'} - {@code 'f'}
1121 *     (<tt>'&#92;u0061'</tt> - <tt>'&#92;u0066'</tt>).
1122 *
1123 * </table>
1124 *
1125 * <p> If the conversion is {@code 'o'}, {@code 'x'}, or {@code 'X'} and
1126 * both the {@code '#'} and the {@code '0'} flags are given, then result will
1127 * contain the base indicator ({@code '0'} for octal and {@code "0x"} or
1128 * {@code "0X"} for hexadecimal), some number of zeros (based on the width),
1129 * and the value.
1130 *
1131 * <p> If the {@code '0'} flag is given and the value is negative, then the
1132 * zero padding will occur after the sign.
1133 *
1134 * <p> If the {@code '-'} flag is not given, then the space padding will occur
1135 * before the sign.
1136 *
1137 * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and
1138 * Long apply.  The <a href="#intdFlags">default behavior</a> when no flags are
1139 * given is the same as for Byte, Short, Integer, and Long.
1140 *
1141 * <p> The specification of <a href="#intWidth">width</a> is the same as
1142 * defined for Byte, Short, Integer, and Long.
1143 *
1144 * <p> The precision is not applicable.  If precision is specified then an
1145 * {@link IllegalFormatPrecisionException} will be thrown.
1146 *
1147 * <p><a name="dndec"><b> Float and Double</b></a>
1148 *
1149 * <p> The following conversions may be applied to {@code float}, {@link
1150 * Float}, {@code double} and {@link Double}.
1151 *
1152 * <table cellpadding=5 summary="floatConv">
1153 *
1154 * <tr><td valign="top"> {@code 'e'}
1155 *     <td valign="top"> <tt>'&#92;u0065'</tt>
1156 *     <td> Requires the output to be formatted using <a
1157 *     name="scientific">computerized scientific notation</a>.  The <a
1158 *     href="#L10nAlgorithm">localization algorithm</a> is applied.
1159 *
1160 *     <p> The formatting of the magnitude <i>m</i> depends upon its value.
1161 *
1162 *     <p> If <i>m</i> is NaN or infinite, the literal strings "NaN" or
1163 *     "Infinity", respectively, will be output.  These values are not
1164 *     localized.
1165 *
1166 *     <p> If <i>m</i> is positive-zero or negative-zero, then the exponent
1167 *     will be {@code "+00"}.
1168 *
1169 *     <p> Otherwise, the result is a string that represents the sign and
1170 *     magnitude (absolute value) of the argument.  The formatting of the sign
1171 *     is described in the <a href="#L10nAlgorithm">localization
1172 *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
1173 *     value.
1174 *
1175 *     <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup>
1176 *     &lt;= <i>m</i> &lt; 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the
1177 *     mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so
1178 *     that 1 &lt;= <i>a</i> &lt; 10. The magnitude is then represented as the
1179 *     integer part of <i>a</i>, as a single decimal digit, followed by the
1180 *     decimal separator followed by decimal digits representing the fractional
1181 *     part of <i>a</i>, followed by the exponent symbol {@code 'e'}
1182 *     (<tt>'&#92;u0065'</tt>), followed by the sign of the exponent, followed
1183 *     by a representation of <i>n</i> as a decimal integer, as produced by the
1184 *     method {@link Long#toString(long, int)}, and zero-padded to include at
1185 *     least two digits.
1186 *
1187 *     <p> The number of digits in the result for the fractional part of
1188 *     <i>m</i> or <i>a</i> is equal to the precision.  If the precision is not
1189 *     specified then the default value is {@code 6}. If the precision is less
1190 *     than the number of digits which would appear after the decimal point in
1191 *     the string returned by {@link Float#toString(float)} or {@link
1192 *     Double#toString(double)} respectively, then the value will be rounded
1193 *     using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up
1194 *     algorithm}.  Otherwise, zeros may be appended to reach the precision.
1195 *     For a canonical representation of the value, use {@link
1196 *     Float#toString(float)} or {@link Double#toString(double)} as
1197 *     appropriate.
1198 *
1199 *     <p>If the {@code ','} flag is given, then an {@link
1200 *     FormatFlagsConversionMismatchException} will be thrown.
1201 *
1202 * <tr><td valign="top"> {@code 'E'}
1203 *     <td valign="top"> <tt>'&#92;u0045'</tt>
1204 *     <td> The upper-case variant of {@code 'e'}.  The exponent symbol
1205 *     will be {@code 'E'} (<tt>'&#92;u0045'</tt>).
1206 *
1207 * <tr><td valign="top"> {@code 'g'}
1208 *     <td valign="top"> <tt>'&#92;u0067'</tt>
1209 *     <td> Requires the output to be formatted in general scientific notation
1210 *     as described below. The <a href="#L10nAlgorithm">localization
1211 *     algorithm</a> is applied.
1212 *
1213 *     <p> After rounding for the precision, the formatting of the resulting
1214 *     magnitude <i>m</i> depends on its value.
1215 *
1216 *     <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less
1217 *     than 10<sup>precision</sup> then it is represented in <i><a
1218 *     href="#decimal">decimal format</a></i>.
1219 *
1220 *     <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to
1221 *     10<sup>precision</sup>, then it is represented in <i><a
1222 *     href="#scientific">computerized scientific notation</a></i>.
1223 *
1224 *     <p> The total number of significant digits in <i>m</i> is equal to the
1225 *     precision.  If the precision is not specified, then the default value is
1226 *     {@code 6}.  If the precision is {@code 0}, then it is taken to be
1227 *     {@code 1}.
1228 *
1229 *     <p> If the {@code '#'} flag is given then an {@link
1230 *     FormatFlagsConversionMismatchException} will be thrown.
1231 *
1232 * <tr><td valign="top"> {@code 'G'}
1233 *     <td valign="top"> <tt>'&#92;u0047'</tt>
1234 *     <td> The upper-case variant of {@code 'g'}.
1235 *
1236 * <tr><td valign="top"> {@code 'f'}
1237 *     <td valign="top"> <tt>'&#92;u0066'</tt>
1238 *     <td> Requires the output to be formatted using <a name="decimal">decimal
1239 *     format</a>.  The <a href="#L10nAlgorithm">localization algorithm</a> is
1240 *     applied.
1241 *
1242 *     <p> The result is a string that represents the sign and magnitude
1243 *     (absolute value) of the argument.  The formatting of the sign is
1244 *     described in the <a href="#L10nAlgorithm">localization
1245 *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
1246 *     value.
1247 *
1248 *     <p> If <i>m</i> NaN or infinite, the literal strings "NaN" or
1249 *     "Infinity", respectively, will be output.  These values are not
1250 *     localized.
1251 *
1252 *     <p> The magnitude is formatted as the integer part of <i>m</i>, with no
1253 *     leading zeroes, followed by the decimal separator followed by one or
1254 *     more decimal digits representing the fractional part of <i>m</i>.
1255 *
1256 *     <p> The number of digits in the result for the fractional part of
1257 *     <i>m</i> or <i>a</i> is equal to the precision.  If the precision is not
1258 *     specified then the default value is {@code 6}. If the precision is less
1259 *     than the number of digits which would appear after the decimal point in
1260 *     the string returned by {@link Float#toString(float)} or {@link
1261 *     Double#toString(double)} respectively, then the value will be rounded
1262 *     using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up
1263 *     algorithm}.  Otherwise, zeros may be appended to reach the precision.
1264 *     For a canonical representation of the value, use {@link
1265 *     Float#toString(float)} or {@link Double#toString(double)} as
1266 *     appropriate.
1267 *
1268 * <tr><td valign="top"> {@code 'a'}
1269 *     <td valign="top"> <tt>'&#92;u0061'</tt>
1270 *     <td> Requires the output to be formatted in hexadecimal exponential
1271 *     form.  No localization is applied.
1272 *
1273 *     <p> The result is a string that represents the sign and magnitude
1274 *     (absolute value) of the argument <i>x</i>.
1275 *
1276 *     <p> If <i>x</i> is negative or a negative-zero value then the result
1277 *     will begin with {@code '-'} (<tt>'&#92;u002d'</tt>).
1278 *
1279 *     <p> If <i>x</i> is positive or a positive-zero value and the
1280 *     {@code '+'} flag is given then the result will begin with {@code '+'}
1281 *     (<tt>'&#92;u002b'</tt>).
1282 *
1283 *     <p> The formatting of the magnitude <i>m</i> depends upon its value.
1284 *
1285 *     <ul>
1286 *
1287 *     <li> If the value is NaN or infinite, the literal strings "NaN" or
1288 *     "Infinity", respectively, will be output.
1289 *
1290 *     <li> If <i>m</i> is zero then it is represented by the string
1291 *     {@code "0x0.0p0"}.
1292 *
1293 *     <li> If <i>m</i> is a {@code double} value with a normalized
1294 *     representation then substrings are used to represent the significand and
1295 *     exponent fields.  The significand is represented by the characters
1296 *     {@code "0x1."} followed by the hexadecimal representation of the rest
1297 *     of the significand as a fraction.  The exponent is represented by
1298 *     {@code 'p'} (<tt>'&#92;u0070'</tt>) followed by a decimal string of the
1299 *     unbiased exponent as if produced by invoking {@link
1300 *     Integer#toString(int) Integer.toString} on the exponent value.  If the
1301 *     precision is specified, the value is rounded to the given number of
1302 *     hexadecimal digits.
1303 *
1304 *     <li> If <i>m</i> is a {@code double} value with a subnormal
1305 *     representation then, unless the precision is specified to be in the range
1306 *     1 through 12, inclusive, the significand is represented by the characters
1307 *     {@code '0x0.'} followed by the hexadecimal representation of the rest of
1308 *     the significand as a fraction, and the exponent represented by
1309 *     {@code 'p-1022'}.  If the precision is in the interval
1310 *     [1,&nbsp;12], the subnormal value is normalized such that it
1311 *     begins with the characters {@code '0x1.'}, rounded to the number of
1312 *     hexadecimal digits of precision, and the exponent adjusted
1313 *     accordingly.  Note that there must be at least one nonzero digit in a
1314 *     subnormal significand.
1315 *
1316 *     </ul>
1317 *
1318 *     <p> If the {@code '('} or {@code ','} flags are given, then a {@link
1319 *     FormatFlagsConversionMismatchException} will be thrown.
1320 *
1321 * <tr><td valign="top"> {@code 'A'}
1322 *     <td valign="top"> <tt>'&#92;u0041'</tt>
1323 *     <td> The upper-case variant of {@code 'a'}.  The entire string
1324 *     representing the number will be converted to upper case including the
1325 *     {@code 'x'} (<tt>'&#92;u0078'</tt>) and {@code 'p'}
1326 *     (<tt>'&#92;u0070'</tt> and all hexadecimal digits {@code 'a'} -
1327 *     {@code 'f'} (<tt>'&#92;u0061'</tt> - <tt>'&#92;u0066'</tt>).
1328 *
1329 * </table>
1330 *
1331 * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and
1332 * Long apply.
1333 *
1334 * <p> If the {@code '#'} flag is given, then the decimal separator will
1335 * always be present.
1336 *
1337 * <p> If no <a name="floatdFlags">flags</a> are given the default formatting
1338 * is as follows:
1339 *
1340 * <ul>
1341 *
1342 * <li> The output is right-justified within the {@code width}
1343 *
1344 * <li> Negative numbers begin with a {@code '-'}
1345 *
1346 * <li> Positive numbers and positive zero do not include a sign or extra
1347 * leading space
1348 *
1349 * <li> No grouping separators are included
1350 *
1351 * <li> The decimal separator will only appear if a digit follows it
1352 *
1353 * </ul>
1354 *
1355 * <p> The <a name="floatDWidth">width</a> is the minimum number of characters
1356 * to be written to the output.  This includes any signs, digits, grouping
1357 * separators, decimal separators, exponential symbol, radix indicator,
1358 * parentheses, and strings representing infinity and NaN as applicable.  If
1359 * the length of the converted value is less than the width then the output
1360 * will be padded by spaces (<tt>'&#92;u0020'</tt>) until the total number of
1361 * characters equals width.  The padding is on the left by default.  If the
1362 * {@code '-'} flag is given then the padding will be on the right.  If width
1363 * is not specified then there is no minimum.
1364 *
1365 * <p> If the <a name="floatDPrec">conversion</a> is {@code 'e'},
1366 * {@code 'E'} or {@code 'f'}, then the precision is the number of digits
1367 * after the decimal separator.  If the precision is not specified, then it is
1368 * assumed to be {@code 6}.
1369 *
1370 * <p> If the conversion is {@code 'g'} or {@code 'G'}, then the precision is
1371 * the total number of significant digits in the resulting magnitude after
1372 * rounding.  If the precision is not specified, then the default value is
1373 * {@code 6}.  If the precision is {@code 0}, then it is taken to be
1374 * {@code 1}.
1375 *
1376 * <p> If the conversion is {@code 'a'} or {@code 'A'}, then the precision
1377 * is the number of hexadecimal digits after the radix point.  If the
1378 * precision is not provided, then all of the digits as returned by {@link
1379 * Double#toHexString(double)} will be output.
1380 *
1381 * <p><a name="dnbdec"><b> BigDecimal </b></a>
1382 *
1383 * <p> The following conversions may be applied {@link java.math.BigDecimal
1384 * BigDecimal}.
1385 *
1386 * <table cellpadding=5 summary="floatConv">
1387 *
1388 * <tr><td valign="top"> {@code 'e'}
1389 *     <td valign="top"> <tt>'&#92;u0065'</tt>
1390 *     <td> Requires the output to be formatted using <a
1391 *     name="bscientific">computerized scientific notation</a>.  The <a
1392 *     href="#L10nAlgorithm">localization algorithm</a> is applied.
1393 *
1394 *     <p> The formatting of the magnitude <i>m</i> depends upon its value.
1395 *
1396 *     <p> If <i>m</i> is positive-zero or negative-zero, then the exponent
1397 *     will be {@code "+00"}.
1398 *
1399 *     <p> Otherwise, the result is a string that represents the sign and
1400 *     magnitude (absolute value) of the argument.  The formatting of the sign
1401 *     is described in the <a href="#L10nAlgorithm">localization
1402 *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
1403 *     value.
1404 *
1405 *     <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup>
1406 *     &lt;= <i>m</i> &lt; 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the
1407 *     mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so
1408 *     that 1 &lt;= <i>a</i> &lt; 10. The magnitude is then represented as the
1409 *     integer part of <i>a</i>, as a single decimal digit, followed by the
1410 *     decimal separator followed by decimal digits representing the fractional
1411 *     part of <i>a</i>, followed by the exponent symbol {@code 'e'}
1412 *     (<tt>'&#92;u0065'</tt>), followed by the sign of the exponent, followed
1413 *     by a representation of <i>n</i> as a decimal integer, as produced by the
1414 *     method {@link Long#toString(long, int)}, and zero-padded to include at
1415 *     least two digits.
1416 *
1417 *     <p> The number of digits in the result for the fractional part of
1418 *     <i>m</i> or <i>a</i> is equal to the precision.  If the precision is not
1419 *     specified then the default value is {@code 6}.  If the precision is
1420 *     less than the number of digits to the right of the decimal point then
1421 *     the value will be rounded using the
1422 *     {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up
1423 *     algorithm}.  Otherwise, zeros may be appended to reach the precision.
1424 *     For a canonical representation of the value, use {@link
1425 *     BigDecimal#toString()}.
1426 *
1427 *     <p> If the {@code ','} flag is given, then an {@link
1428 *     FormatFlagsConversionMismatchException} will be thrown.
1429 *
1430 * <tr><td valign="top"> {@code 'E'}
1431 *     <td valign="top"> <tt>'&#92;u0045'</tt>
1432 *     <td> The upper-case variant of {@code 'e'}.  The exponent symbol
1433 *     will be {@code 'E'} (<tt>'&#92;u0045'</tt>).
1434 *
1435 * <tr><td valign="top"> {@code 'g'}
1436 *     <td valign="top"> <tt>'&#92;u0067'</tt>
1437 *     <td> Requires the output to be formatted in general scientific notation
1438 *     as described below. The <a href="#L10nAlgorithm">localization
1439 *     algorithm</a> is applied.
1440 *
1441 *     <p> After rounding for the precision, the formatting of the resulting
1442 *     magnitude <i>m</i> depends on its value.
1443 *
1444 *     <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less
1445 *     than 10<sup>precision</sup> then it is represented in <i><a
1446 *     href="#bdecimal">decimal format</a></i>.
1447 *
1448 *     <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to
1449 *     10<sup>precision</sup>, then it is represented in <i><a
1450 *     href="#bscientific">computerized scientific notation</a></i>.
1451 *
1452 *     <p> The total number of significant digits in <i>m</i> is equal to the
1453 *     precision.  If the precision is not specified, then the default value is
1454 *     {@code 6}.  If the precision is {@code 0}, then it is taken to be
1455 *     {@code 1}.
1456 *
1457 *     <p> If the {@code '#'} flag is given then an {@link
1458 *     FormatFlagsConversionMismatchException} will be thrown.
1459 *
1460 * <tr><td valign="top"> {@code 'G'}
1461 *     <td valign="top"> <tt>'&#92;u0047'</tt>
1462 *     <td> The upper-case variant of {@code 'g'}.
1463 *
1464 * <tr><td valign="top"> {@code 'f'}
1465 *     <td valign="top"> <tt>'&#92;u0066'</tt>
1466 *     <td> Requires the output to be formatted using <a name="bdecimal">decimal
1467 *     format</a>.  The <a href="#L10nAlgorithm">localization algorithm</a> is
1468 *     applied.
1469 *
1470 *     <p> The result is a string that represents the sign and magnitude
1471 *     (absolute value) of the argument.  The formatting of the sign is
1472 *     described in the <a href="#L10nAlgorithm">localization
1473 *     algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its
1474 *     value.
1475 *
1476 *     <p> The magnitude is formatted as the integer part of <i>m</i>, with no
1477 *     leading zeroes, followed by the decimal separator followed by one or
1478 *     more decimal digits representing the fractional part of <i>m</i>.
1479 *
1480 *     <p> The number of digits in the result for the fractional part of
1481 *     <i>m</i> or <i>a</i> is equal to the precision. If the precision is not
1482 *     specified then the default value is {@code 6}.  If the precision is
1483 *     less than the number of digits to the right of the decimal point
1484 *     then the value will be rounded using the
1485 *     {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up
1486 *     algorithm}.  Otherwise, zeros may be appended to reach the precision.
1487 *     For a canonical representation of the value, use {@link
1488 *     BigDecimal#toString()}.
1489 *
1490 * </table>
1491 *
1492 * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and
1493 * Long apply.
1494 *
1495 * <p> If the {@code '#'} flag is given, then the decimal separator will
1496 * always be present.
1497 *
1498 * <p> The <a href="#floatdFlags">default behavior</a> when no flags are
1499 * given is the same as for Float and Double.
1500 *
1501 * <p> The specification of <a href="#floatDWidth">width</a> and <a
1502 * href="#floatDPrec">precision</a> is the same as defined for Float and
1503 * Double.
1504 *
1505 * <h4><a name="ddt">Date/Time</a></h4>
1506 *
1507 * <p> This conversion may be applied to {@code long}, {@link Long}, {@link
1508 * Calendar}, {@link Date} and {@link TemporalAccessor TemporalAccessor}
1509 *
1510 * <table cellpadding=5 summary="DTConv">
1511 *
1512 * <tr><td valign="top"> {@code 't'}
1513 *     <td valign="top"> <tt>'&#92;u0074'</tt>
1514 *     <td> Prefix for date and time conversion characters.
1515 * <tr><td valign="top"> {@code 'T'}
1516 *     <td valign="top"> <tt>'&#92;u0054'</tt>
1517 *     <td> The upper-case variant of {@code 't'}.
1518 *
1519 * </table>
1520 *
1521 * <p> The following date and time conversion character suffixes are defined
1522 * for the {@code 't'} and {@code 'T'} conversions.  The types are similar to
1523 * but not completely identical to those defined by GNU {@code date} and
1524 * POSIX {@code strftime(3c)}.  Additional conversion types are provided to
1525 * access Java-specific functionality (e.g. {@code 'L'} for milliseconds
1526 * within the second).
1527 *
1528 * <p> The following conversion characters are used for formatting times:
1529 *
1530 * <table cellpadding=5 summary="time">
1531 *
1532 * <tr><td valign="top"> {@code 'H'}
1533 *     <td valign="top"> <tt>'&#92;u0048'</tt>
1534 *     <td> Hour of the day for the 24-hour clock, formatted as two digits with
1535 *     a leading zero as necessary i.e. {@code 00 - 23}. {@code 00}
1536 *     corresponds to midnight.
1537 *
1538 * <tr><td valign="top">{@code 'I'}
1539 *     <td valign="top"> <tt>'&#92;u0049'</tt>
1540 *     <td> Hour for the 12-hour clock, formatted as two digits with a leading
1541 *     zero as necessary, i.e.  {@code 01 - 12}.  {@code 01} corresponds to
1542 *     one o'clock (either morning or afternoon).
1543 *
1544 * <tr><td valign="top">{@code 'k'}
1545 *     <td valign="top"> <tt>'&#92;u006b'</tt>
1546 *     <td> Hour of the day for the 24-hour clock, i.e. {@code 0 - 23}.
1547 *     {@code 0} corresponds to midnight.
1548 *
1549 * <tr><td valign="top">{@code 'l'}
1550 *     <td valign="top"> <tt>'&#92;u006c'</tt>
1551 *     <td> Hour for the 12-hour clock, i.e. {@code 1 - 12}.  {@code 1}
1552 *     corresponds to one o'clock (either morning or afternoon).
1553 *
1554 * <tr><td valign="top">{@code 'M'}
1555 *     <td valign="top"> <tt>'&#92;u004d'</tt>
1556 *     <td> Minute within the hour formatted as two digits with a leading zero
1557 *     as necessary, i.e.  {@code 00 - 59}.
1558 *
1559 * <tr><td valign="top">{@code 'S'}
1560 *     <td valign="top"> <tt>'&#92;u0053'</tt>
1561 *     <td> Seconds within the minute, formatted as two digits with a leading
1562 *     zero as necessary, i.e. {@code 00 - 60} ("{@code 60}" is a special
1563 *     value required to support leap seconds).
1564 *
1565 * <tr><td valign="top">{@code 'L'}
1566 *     <td valign="top"> <tt>'&#92;u004c'</tt>
1567 *     <td> Millisecond within the second formatted as three digits with
1568 *     leading zeros as necessary, i.e. {@code 000 - 999}.
1569 *
1570 * <tr><td valign="top">{@code 'N'}
1571 *     <td valign="top"> <tt>'&#92;u004e'</tt>
1572 *     <td> Nanosecond within the second, formatted as nine digits with leading
1573 *     zeros as necessary, i.e. {@code 000000000 - 999999999}.  The precision
1574 *     of this value is limited by the resolution of the underlying operating
1575 *     system or hardware.
1576 *
1577 * <tr><td valign="top">{@code 'p'}
1578 *     <td valign="top"> <tt>'&#92;u0070'</tt>
1579 *     <td> Locale-specific {@linkplain
1580 *     java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker
1581 *     in lower case, e.g."{@code am}" or "{@code pm}".  Use of the
1582 *     conversion prefix {@code 'T'} forces this output to upper case.  (Note
1583 *     that {@code 'p'} produces lower-case output.  This is different from
1584 *     GNU {@code date} and POSIX {@code strftime(3c)} which produce
1585 *     upper-case output.)
1586 *
1587 * <tr><td valign="top">{@code 'z'}
1588 *     <td valign="top"> <tt>'&#92;u007a'</tt>
1589 *     <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC&nbsp;822</a>
1590 *     style numeric time zone offset from GMT, e.g. {@code -0800}.  This
1591 *     value will be adjusted as necessary for Daylight Saving Time.  For
1592 *     {@code long}, {@link Long}, and {@link Date} the time zone used is
1593 *     the {@linkplain TimeZone#getDefault() default time zone} for this
1594 *     instance of the Java virtual machine.
1595 *
1596 * <tr><td valign="top">{@code 'Z'}
1597 *     <td valign="top"> <tt>'&#92;u005a'</tt>
1598 *     <td> A string representing the abbreviation for the time zone.  This
1599 *     value will be adjusted as necessary for Daylight Saving Time.  For
1600 *     {@code long}, {@link Long}, and {@link Date} the time zone used is
1601 *     the {@linkplain TimeZone#getDefault() default time zone} for this
1602 *     instance of the Java virtual machine.  The Formatter's locale will
1603 *     supersede the locale of the argument (if any).
1604 *
1605 * <tr><td valign="top">{@code 's'}
1606 *     <td valign="top"> <tt>'&#92;u0073'</tt>
1607 *     <td> Seconds since the beginning of the epoch starting at 1 January 1970
1608 *     {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE/1000} to
1609 *     {@code Long.MAX_VALUE/1000}.
1610 *
1611 * <tr><td valign="top">{@code 'Q'}
1612 *     <td valign="top"> <tt>'&#92;u004f'</tt>
1613 *     <td> Milliseconds since the beginning of the epoch starting at 1 January
1614 *     1970 {@code 00:00:00} UTC, i.e. {@code Long.MIN_VALUE} to
1615 *     {@code Long.MAX_VALUE}. The precision of this value is limited by
1616 *     the resolution of the underlying operating system or hardware.
1617 *
1618 * </table>
1619 *
1620 * <p> The following conversion characters are used for formatting dates:
1621 *
1622 * <table cellpadding=5 summary="date">
1623 *
1624 * <tr><td valign="top">{@code 'B'}
1625 *     <td valign="top"> <tt>'&#92;u0042'</tt>
1626 *     <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths
1627 *     full month name}, e.g. {@code "January"}, {@code "February"}.
1628 *
1629 * <tr><td valign="top">{@code 'b'}
1630 *     <td valign="top"> <tt>'&#92;u0062'</tt>
1631 *     <td> Locale-specific {@linkplain
1632 *     java.text.DateFormatSymbols#getShortMonths abbreviated month name},
1633 *     e.g. {@code "Jan"}, {@code "Feb"}.
1634 *
1635 * <tr><td valign="top">{@code 'h'}
1636 *     <td valign="top"> <tt>'&#92;u0068'</tt>
1637 *     <td> Same as {@code 'b'}.
1638 *
1639 * <tr><td valign="top">{@code 'A'}
1640 *     <td valign="top"> <tt>'&#92;u0041'</tt>
1641 *     <td> Locale-specific full name of the {@linkplain
1642 *     java.text.DateFormatSymbols#getWeekdays day of the week},
1643 *     e.g. {@code "Sunday"}, {@code "Monday"}
1644 *
1645 * <tr><td valign="top">{@code 'a'}
1646 *     <td valign="top"> <tt>'&#92;u0061'</tt>
1647 *     <td> Locale-specific short name of the {@linkplain
1648 *     java.text.DateFormatSymbols#getShortWeekdays day of the week},
1649 *     e.g. {@code "Sun"}, {@code "Mon"}
1650 *
1651 * <tr><td valign="top">{@code 'C'}
1652 *     <td valign="top"> <tt>'&#92;u0043'</tt>
1653 *     <td> Four-digit year divided by {@code 100}, formatted as two digits
1654 *     with leading zero as necessary, i.e. {@code 00 - 99}
1655 *
1656 * <tr><td valign="top">{@code 'Y'}
1657 *     <td valign="top"> <tt>'&#92;u0059'</tt> <td> Year, formatted to at least
1658 *     four digits with leading zeros as necessary, e.g. {@code 0092} equals
1659 *     {@code 92} CE for the Gregorian calendar.
1660 *
1661 * <tr><td valign="top">{@code 'y'}
1662 *     <td valign="top"> <tt>'&#92;u0079'</tt>
1663 *     <td> Last two digits of the year, formatted with leading zeros as
1664 *     necessary, i.e. {@code 00 - 99}.
1665 *
1666 * <tr><td valign="top">{@code 'j'}
1667 *     <td valign="top"> <tt>'&#92;u006a'</tt>
1668 *     <td> Day of year, formatted as three digits with leading zeros as
1669 *     necessary, e.g. {@code 001 - 366} for the Gregorian calendar.
1670 *     {@code 001} corresponds to the first day of the year.
1671 *
1672 * <tr><td valign="top">{@code 'm'}
1673 *     <td valign="top"> <tt>'&#92;u006d'</tt>
1674 *     <td> Month, formatted as two digits with leading zeros as necessary,
1675 *     i.e. {@code 01 - 13}, where "{@code 01}" is the first month of the
1676 *     year and ("{@code 13}" is a special value required to support lunar
1677 *     calendars).
1678 *
1679 * <tr><td valign="top">{@code 'd'}
1680 *     <td valign="top"> <tt>'&#92;u0064'</tt>
1681 *     <td> Day of month, formatted as two digits with leading zeros as
1682 *     necessary, i.e. {@code 01 - 31}, where "{@code 01}" is the first day
1683 *     of the month.
1684 *
1685 * <tr><td valign="top">{@code 'e'}
1686 *     <td valign="top"> <tt>'&#92;u0065'</tt>
1687 *     <td> Day of month, formatted as two digits, i.e. {@code 1 - 31} where
1688 *     "{@code 1}" is the first day of the month.
1689 *
1690 * </table>
1691 *
1692 * <p> The following conversion characters are used for formatting common
1693 * date/time compositions.
1694 *
1695 * <table cellpadding=5 summary="composites">
1696 *
1697 * <tr><td valign="top">{@code 'R'}
1698 *     <td valign="top"> <tt>'&#92;u0052'</tt>
1699 *     <td> Time formatted for the 24-hour clock as {@code "%tH:%tM"}
1700 *
1701 * <tr><td valign="top">{@code 'T'}
1702 *     <td valign="top"> <tt>'&#92;u0054'</tt>
1703 *     <td> Time formatted for the 24-hour clock as {@code "%tH:%tM:%tS"}.
1704 *
1705 * <tr><td valign="top">{@code 'r'}
1706 *     <td valign="top"> <tt>'&#92;u0072'</tt>
1707 *     <td> Time formatted for the 12-hour clock as {@code "%tI:%tM:%tS
1708 *     %Tp"}.  The location of the morning or afternoon marker
1709 *     ({@code '%Tp'}) may be locale-dependent.
1710 *
1711 * <tr><td valign="top">{@code 'D'}
1712 *     <td valign="top"> <tt>'&#92;u0044'</tt>
1713 *     <td> Date formatted as {@code "%tm/%td/%ty"}.
1714 *
1715 * <tr><td valign="top">{@code 'F'}
1716 *     <td valign="top"> <tt>'&#92;u0046'</tt>
1717 *     <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO&nbsp;8601</a>
1718 *     complete date formatted as {@code "%tY-%tm-%td"}.
1719 *
1720 * <tr><td valign="top">{@code 'c'}
1721 *     <td valign="top"> <tt>'&#92;u0063'</tt>
1722 *     <td> Date and time formatted as {@code "%ta %tb %td %tT %tZ %tY"},
1723 *     e.g. {@code "Sun Jul 20 16:17:00 EDT 1969"}.
1724 *
1725 * </table>
1726 *
1727 * <p> The {@code '-'} flag defined for <a href="#dFlags">General
1728 * conversions</a> applies.  If the {@code '#'} flag is given, then a {@link
1729 * FormatFlagsConversionMismatchException} will be thrown.
1730 *
1731 * <p> The width is the minimum number of characters to
1732 * be written to the output.  If the length of the converted value is less than
1733 * the {@code width} then the output will be padded by spaces
1734 * (<tt>'&#92;u0020'</tt>) until the total number of characters equals width.
1735 * The padding is on the left by default.  If the {@code '-'} flag is given
1736 * then the padding will be on the right.  If width is not specified then there
1737 * is no minimum.
1738 *
1739 * <p> The precision is not applicable.  If the precision is specified then an
1740 * {@link IllegalFormatPrecisionException} will be thrown.
1741 *
1742 * <h4><a name="dper">Percent</a></h4>
1743 *
1744 * <p> The conversion does not correspond to any argument.
1745 *
1746 * <table cellpadding=5 summary="DTConv">
1747 *
1748 * <tr><td valign="top">{@code '%'}
1749 *     <td> The result is a literal {@code '%'} (<tt>'&#92;u0025'</tt>)
1750 *
1751 * <p> The width is the minimum number of characters to
1752 * be written to the output including the {@code '%'}.  If the length of the
1753 * converted value is less than the {@code width} then the output will be
1754 * padded by spaces (<tt>'&#92;u0020'</tt>) until the total number of
1755 * characters equals width.  The padding is on the left.  If width is not
1756 * specified then just the {@code '%'} is output.
1757 *
1758 * <p> The {@code '-'} flag defined for <a href="#dFlags">General
1759 * conversions</a> applies.  If any other flags are provided, then a
1760 * {@link FormatFlagsConversionMismatchException} will be thrown.
1761 *
1762 * <p> The precision is not applicable.  If the precision is specified an
1763 * {@link IllegalFormatPrecisionException} will be thrown.
1764 *
1765 * </table>
1766 *
1767 * <h4><a name="dls">Line Separator</a></h4>
1768 *
1769 * <p> The conversion does not correspond to any argument.
1770 *
1771 * <table cellpadding=5 summary="DTConv">
1772 *
1773 * <tr><td valign="top">{@code 'n'}
1774 *     <td> the platform-specific line separator as returned by {@link
1775 *     System#getProperty System.getProperty("line.separator")}.
1776 *
1777 * </table>
1778 *
1779 * <p> Flags, width, and precision are not applicable.  If any are provided an
1780 * {@link IllegalFormatFlagsException}, {@link IllegalFormatWidthException},
1781 * and {@link IllegalFormatPrecisionException}, respectively will be thrown.
1782 *
1783 * <h4><a name="dpos">Argument Index</a></h4>
1784 *
1785 * <p> Format specifiers can reference arguments in three ways:
1786 *
1787 * <ul>
1788 *
1789 * <li> <i>Explicit indexing</i> is used when the format specifier contains an
1790 * argument index.  The argument index is a decimal integer indicating the
1791 * position of the argument in the argument list.  The first argument is
1792 * referenced by "{@code 1$}", the second by "{@code 2$}", etc.  An argument
1793 * may be referenced more than once.
1794 *
1795 * <p> For example:
1796 *
1797 * <blockquote><pre>
1798 *   formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",
1799 *                    "a", "b", "c", "d")
1800 *   // -&gt; "d c b a d c b a"
1801 * </pre></blockquote>
1802 *
1803 * <li> <i>Relative indexing</i> is used when the format specifier contains a
1804 * {@code '<'} (<tt>'&#92;u003c'</tt>) flag which causes the argument for
1805 * the previous format specifier to be re-used.  If there is no previous
1806 * argument, then a {@link MissingFormatArgumentException} is thrown.
1807 *
1808 * <blockquote><pre>
1809 *    formatter.format("%s %s %&lt;s %&lt;s", "a", "b", "c", "d")
1810 *    // -&gt; "a b b b"
1811 *    // "c" and "d" are ignored because they are not referenced
1812 * </pre></blockquote>
1813 *
1814 * <li> <i>Ordinary indexing</i> is used when the format specifier contains
1815 * neither an argument index nor a {@code '<'} flag.  Each format specifier
1816 * which uses ordinary indexing is assigned a sequential implicit index into
1817 * argument list which is independent of the indices used by explicit or
1818 * relative indexing.
1819 *
1820 * <blockquote><pre>
1821 *   formatter.format("%s %s %s %s", "a", "b", "c", "d")
1822 *   // -&gt; "a b c d"
1823 * </pre></blockquote>
1824 *
1825 * </ul>
1826 *
1827 * <p> It is possible to have a format string which uses all forms of indexing,
1828 * for example:
1829 *
1830 * <blockquote><pre>
1831 *   formatter.format("%2$s %s %&lt;s %s", "a", "b", "c", "d")
1832 *   // -&gt; "b a a b"
1833 *   // "c" and "d" are ignored because they are not referenced
1834 * </pre></blockquote>
1835 *
1836 * <p> The maximum number of arguments is limited by the maximum dimension of a
1837 * Java array as defined by
1838 * <cite>The Java&trade; Virtual Machine Specification</cite>.
1839 * If the argument index does not correspond to an
1840 * available argument, then a {@link MissingFormatArgumentException} is thrown.
1841 *
1842 * <p> If there are more arguments than format specifiers, the extra arguments
1843 * are ignored.
1844 *
1845 * <p> Unless otherwise specified, passing a {@code null} argument to any
1846 * method or constructor in this class will cause a {@link
1847 * NullPointerException} to be thrown.
1848 *
1849 * @author  Iris Clark
1850 * @since 1.5
1851 */
1852public final class Formatter implements Closeable, Flushable {
1853    private Appendable a;
1854    private final Locale l;
1855
1856    private IOException lastException;
1857
1858    private final char zero;
1859    private static double scaleUp;
1860
1861    // 1 (sign) + 19 (max # sig digits) + 1 ('.') + 1 ('e') + 1 (sign)
1862    // + 3 (max # exp digits) + 4 (error) = 30
1863    private static final int MAX_FD_CHARS = 30;
1864
1865    /**
1866     * Returns a charset object for the given charset name.
1867     * @throws NullPointerException          is csn is null
1868     * @throws UnsupportedEncodingException  if the charset is not supported
1869     */
1870    private static Charset toCharset(String csn)
1871        throws UnsupportedEncodingException
1872    {
1873        Objects.requireNonNull(csn, "charsetName");
1874        try {
1875            return Charset.forName(csn);
1876        } catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {
1877            // UnsupportedEncodingException should be thrown
1878            throw new UnsupportedEncodingException(csn);
1879        }
1880    }
1881
1882    private static final Appendable nonNullAppendable(Appendable a) {
1883        if (a == null)
1884            return new StringBuilder();
1885
1886        return a;
1887    }
1888
1889    /* Private constructors */
1890    private Formatter(Locale l, Appendable a) {
1891        this.a = a;
1892        this.l = l;
1893        this.zero = getZero(l);
1894    }
1895
1896    private Formatter(Charset charset, Locale l, File file)
1897        throws FileNotFoundException
1898    {
1899        this(l,
1900             new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)));
1901    }
1902
1903    /**
1904     * Constructs a new formatter.
1905     *
1906     * <p> The destination of the formatted output is a {@link StringBuilder}
1907     * which may be retrieved by invoking {@link #out out()} and whose
1908     * current content may be converted into a string by invoking {@link
1909     * #toString toString()}.  The locale used is the {@linkplain
1910     * Locale#getDefault(Locale.Category) default locale} for
1911     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
1912     * virtual machine.
1913     */
1914    public Formatter() {
1915        this(Locale.getDefault(Locale.Category.FORMAT), new StringBuilder());
1916    }
1917
1918    /**
1919     * Constructs a new formatter with the specified destination.
1920     *
1921     * <p> The locale used is the {@linkplain
1922     * Locale#getDefault(Locale.Category) default locale} for
1923     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
1924     * virtual machine.
1925     *
1926     * @param  a
1927     *         Destination for the formatted output.  If {@code a} is
1928     *         {@code null} then a {@link StringBuilder} will be created.
1929     */
1930    public Formatter(Appendable a) {
1931        this(Locale.getDefault(Locale.Category.FORMAT), nonNullAppendable(a));
1932    }
1933
1934    /**
1935     * Constructs a new formatter with the specified locale.
1936     *
1937     * <p> The destination of the formatted output is a {@link StringBuilder}
1938     * which may be retrieved by invoking {@link #out out()} and whose current
1939     * content may be converted into a string by invoking {@link #toString
1940     * toString()}.
1941     *
1942     * @param  l
1943     *         The {@linkplain java.util.Locale locale} to apply during
1944     *         formatting.  If {@code l} is {@code null} then no localization
1945     *         is applied.
1946     */
1947    public Formatter(Locale l) {
1948        this(l, new StringBuilder());
1949    }
1950
1951    /**
1952     * Constructs a new formatter with the specified destination and locale.
1953     *
1954     * @param  a
1955     *         Destination for the formatted output.  If {@code a} is
1956     *         {@code null} then a {@link StringBuilder} will be created.
1957     *
1958     * @param  l
1959     *         The {@linkplain java.util.Locale locale} to apply during
1960     *         formatting.  If {@code l} is {@code null} then no localization
1961     *         is applied.
1962     */
1963    public Formatter(Appendable a, Locale l) {
1964        this(l, nonNullAppendable(a));
1965    }
1966
1967    /**
1968     * Constructs a new formatter with the specified file name.
1969     *
1970     * <p> The charset used is the {@linkplain
1971     * java.nio.charset.Charset#defaultCharset() default charset} for this
1972     * instance of the Java virtual machine.
1973     *
1974     * <p> The locale used is the {@linkplain
1975     * Locale#getDefault(Locale.Category) default locale} for
1976     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
1977     * virtual machine.
1978     *
1979     * @param  fileName
1980     *         The name of the file to use as the destination of this
1981     *         formatter.  If the file exists then it will be truncated to
1982     *         zero size; otherwise, a new file will be created.  The output
1983     *         will be written to the file and is buffered.
1984     *
1985     * @throws  SecurityException
1986     *          If a security manager is present and {@link
1987     *          SecurityManager#checkWrite checkWrite(fileName)} denies write
1988     *          access to the file
1989     *
1990     * @throws  FileNotFoundException
1991     *          If the given file name does not denote an existing, writable
1992     *          regular file and a new regular file of that name cannot be
1993     *          created, or if some other error occurs while opening or
1994     *          creating the file
1995     */
1996    public Formatter(String fileName) throws FileNotFoundException {
1997        this(Locale.getDefault(Locale.Category.FORMAT),
1998             new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))));
1999    }
2000
2001    /**
2002     * Constructs a new formatter with the specified file name and charset.
2003     *
2004     * <p> The locale used is the {@linkplain
2005     * Locale#getDefault(Locale.Category) default locale} for
2006     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
2007     * virtual machine.
2008     *
2009     * @param  fileName
2010     *         The name of the file to use as the destination of this
2011     *         formatter.  If the file exists then it will be truncated to
2012     *         zero size; otherwise, a new file will be created.  The output
2013     *         will be written to the file and is buffered.
2014     *
2015     * @param  csn
2016     *         The name of a supported {@linkplain java.nio.charset.Charset
2017     *         charset}
2018     *
2019     * @throws  FileNotFoundException
2020     *          If the given file name does not denote an existing, writable
2021     *          regular file and a new regular file of that name cannot be
2022     *          created, or if some other error occurs while opening or
2023     *          creating the file
2024     *
2025     * @throws  SecurityException
2026     *          If a security manager is present and {@link
2027     *          SecurityManager#checkWrite checkWrite(fileName)} denies write
2028     *          access to the file
2029     *
2030     * @throws  UnsupportedEncodingException
2031     *          If the named charset is not supported
2032     */
2033    public Formatter(String fileName, String csn)
2034        throws FileNotFoundException, UnsupportedEncodingException
2035    {
2036        this(fileName, csn, Locale.getDefault(Locale.Category.FORMAT));
2037    }
2038
2039    /**
2040     * Constructs a new formatter with the specified file name, charset, and
2041     * locale.
2042     *
2043     * @param  fileName
2044     *         The name of the file to use as the destination of this
2045     *         formatter.  If the file exists then it will be truncated to
2046     *         zero size; otherwise, a new file will be created.  The output
2047     *         will be written to the file and is buffered.
2048     *
2049     * @param  csn
2050     *         The name of a supported {@linkplain java.nio.charset.Charset
2051     *         charset}
2052     *
2053     * @param  l
2054     *         The {@linkplain java.util.Locale locale} to apply during
2055     *         formatting.  If {@code l} is {@code null} then no localization
2056     *         is applied.
2057     *
2058     * @throws  FileNotFoundException
2059     *          If the given file name does not denote an existing, writable
2060     *          regular file and a new regular file of that name cannot be
2061     *          created, or if some other error occurs while opening or
2062     *          creating the file
2063     *
2064     * @throws  SecurityException
2065     *          If a security manager is present and {@link
2066     *          SecurityManager#checkWrite checkWrite(fileName)} denies write
2067     *          access to the file
2068     *
2069     * @throws  UnsupportedEncodingException
2070     *          If the named charset is not supported
2071     */
2072    public Formatter(String fileName, String csn, Locale l)
2073        throws FileNotFoundException, UnsupportedEncodingException
2074    {
2075        this(toCharset(csn), l, new File(fileName));
2076    }
2077
2078    /**
2079     * Constructs a new formatter with the specified file.
2080     *
2081     * <p> The charset used is the {@linkplain
2082     * java.nio.charset.Charset#defaultCharset() default charset} for this
2083     * instance of the Java virtual machine.
2084     *
2085     * <p> The locale used is the {@linkplain
2086     * Locale#getDefault(Locale.Category) default locale} for
2087     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
2088     * virtual machine.
2089     *
2090     * @param  file
2091     *         The file to use as the destination of this formatter.  If the
2092     *         file exists then it will be truncated to zero size; otherwise,
2093     *         a new file will be created.  The output will be written to the
2094     *         file and is buffered.
2095     *
2096     * @throws  SecurityException
2097     *          If a security manager is present and {@link
2098     *          SecurityManager#checkWrite checkWrite(file.getPath())} denies
2099     *          write access to the file
2100     *
2101     * @throws  FileNotFoundException
2102     *          If the given file object does not denote an existing, writable
2103     *          regular file and a new regular file of that name cannot be
2104     *          created, or if some other error occurs while opening or
2105     *          creating the file
2106     */
2107    public Formatter(File file) throws FileNotFoundException {
2108        this(Locale.getDefault(Locale.Category.FORMAT),
2109             new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))));
2110    }
2111
2112    /**
2113     * Constructs a new formatter with the specified file and charset.
2114     *
2115     * <p> The locale used is the {@linkplain
2116     * Locale#getDefault(Locale.Category) default locale} for
2117     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
2118     * virtual machine.
2119     *
2120     * @param  file
2121     *         The file to use as the destination of this formatter.  If the
2122     *         file exists then it will be truncated to zero size; otherwise,
2123     *         a new file will be created.  The output will be written to the
2124     *         file and is buffered.
2125     *
2126     * @param  csn
2127     *         The name of a supported {@linkplain java.nio.charset.Charset
2128     *         charset}
2129     *
2130     * @throws  FileNotFoundException
2131     *          If the given file object does not denote an existing, writable
2132     *          regular file and a new regular file of that name cannot be
2133     *          created, or if some other error occurs while opening or
2134     *          creating the file
2135     *
2136     * @throws  SecurityException
2137     *          If a security manager is present and {@link
2138     *          SecurityManager#checkWrite checkWrite(file.getPath())} denies
2139     *          write access to the file
2140     *
2141     * @throws  UnsupportedEncodingException
2142     *          If the named charset is not supported
2143     */
2144    public Formatter(File file, String csn)
2145        throws FileNotFoundException, UnsupportedEncodingException
2146    {
2147        this(file, csn, Locale.getDefault(Locale.Category.FORMAT));
2148    }
2149
2150    /**
2151     * Constructs a new formatter with the specified file, charset, and
2152     * locale.
2153     *
2154     * @param  file
2155     *         The file to use as the destination of this formatter.  If the
2156     *         file exists then it will be truncated to zero size; otherwise,
2157     *         a new file will be created.  The output will be written to the
2158     *         file and is buffered.
2159     *
2160     * @param  csn
2161     *         The name of a supported {@linkplain java.nio.charset.Charset
2162     *         charset}
2163     *
2164     * @param  l
2165     *         The {@linkplain java.util.Locale locale} to apply during
2166     *         formatting.  If {@code l} is {@code null} then no localization
2167     *         is applied.
2168     *
2169     * @throws  FileNotFoundException
2170     *          If the given file object does not denote an existing, writable
2171     *          regular file and a new regular file of that name cannot be
2172     *          created, or if some other error occurs while opening or
2173     *          creating the file
2174     *
2175     * @throws  SecurityException
2176     *          If a security manager is present and {@link
2177     *          SecurityManager#checkWrite checkWrite(file.getPath())} denies
2178     *          write access to the file
2179     *
2180     * @throws  UnsupportedEncodingException
2181     *          If the named charset is not supported
2182     */
2183    public Formatter(File file, String csn, Locale l)
2184        throws FileNotFoundException, UnsupportedEncodingException
2185    {
2186        this(toCharset(csn), l, file);
2187    }
2188
2189    /**
2190     * Constructs a new formatter with the specified print stream.
2191     *
2192     * <p> The locale used is the {@linkplain
2193     * Locale#getDefault(Locale.Category) default locale} for
2194     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
2195     * virtual machine.
2196     *
2197     * <p> Characters are written to the given {@link java.io.PrintStream
2198     * PrintStream} object and are therefore encoded using that object's
2199     * charset.
2200     *
2201     * @param  ps
2202     *         The stream to use as the destination of this formatter.
2203     */
2204    public Formatter(PrintStream ps) {
2205        this(Locale.getDefault(Locale.Category.FORMAT),
2206             (Appendable)Objects.requireNonNull(ps));
2207    }
2208
2209    /**
2210     * Constructs a new formatter with the specified output stream.
2211     *
2212     * <p> The charset used is the {@linkplain
2213     * java.nio.charset.Charset#defaultCharset() default charset} for this
2214     * instance of the Java virtual machine.
2215     *
2216     * <p> The locale used is the {@linkplain
2217     * Locale#getDefault(Locale.Category) default locale} for
2218     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
2219     * virtual machine.
2220     *
2221     * @param  os
2222     *         The output stream to use as the destination of this formatter.
2223     *         The output will be buffered.
2224     */
2225    public Formatter(OutputStream os) {
2226        this(Locale.getDefault(Locale.Category.FORMAT),
2227             new BufferedWriter(new OutputStreamWriter(os)));
2228    }
2229
2230    /**
2231     * Constructs a new formatter with the specified output stream and
2232     * charset.
2233     *
2234     * <p> The locale used is the {@linkplain
2235     * Locale#getDefault(Locale.Category) default locale} for
2236     * {@linkplain Locale.Category#FORMAT formatting} for this instance of the Java
2237     * virtual machine.
2238     *
2239     * @param  os
2240     *         The output stream to use as the destination of this formatter.
2241     *         The output will be buffered.
2242     *
2243     * @param  csn
2244     *         The name of a supported {@linkplain java.nio.charset.Charset
2245     *         charset}
2246     *
2247     * @throws  UnsupportedEncodingException
2248     *          If the named charset is not supported
2249     */
2250    public Formatter(OutputStream os, String csn)
2251        throws UnsupportedEncodingException
2252    {
2253        this(os, csn, Locale.getDefault(Locale.Category.FORMAT));
2254    }
2255
2256    /**
2257     * Constructs a new formatter with the specified output stream, charset,
2258     * and locale.
2259     *
2260     * @param  os
2261     *         The output stream to use as the destination of this formatter.
2262     *         The output will be buffered.
2263     *
2264     * @param  csn
2265     *         The name of a supported {@linkplain java.nio.charset.Charset
2266     *         charset}
2267     *
2268     * @param  l
2269     *         The {@linkplain java.util.Locale locale} to apply during
2270     *         formatting.  If {@code l} is {@code null} then no localization
2271     *         is applied.
2272     *
2273     * @throws  UnsupportedEncodingException
2274     *          If the named charset is not supported
2275     */
2276    public Formatter(OutputStream os, String csn, Locale l)
2277        throws UnsupportedEncodingException
2278    {
2279        this(l, new BufferedWriter(new OutputStreamWriter(os, csn)));
2280    }
2281
2282    private static char getZero(Locale l) {
2283        if ((l != null) && !l.equals(Locale.US)) {
2284            DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
2285            return dfs.getZeroDigit();
2286        } else {
2287            return '0';
2288        }
2289    }
2290
2291    /**
2292     * Returns the locale set by the construction of this formatter.
2293     *
2294     * <p> The {@link #format(java.util.Locale,String,Object...) format} method
2295     * for this object which has a locale argument does not change this value.
2296     *
2297     * @return  {@code null} if no localization is applied, otherwise a
2298     *          locale
2299     *
2300     * @throws  FormatterClosedException
2301     *          If this formatter has been closed by invoking its {@link
2302     *          #close()} method
2303     */
2304    public Locale locale() {
2305        ensureOpen();
2306        return l;
2307    }
2308
2309    /**
2310     * Returns the destination for the output.
2311     *
2312     * @return  The destination for the output
2313     *
2314     * @throws  FormatterClosedException
2315     *          If this formatter has been closed by invoking its {@link
2316     *          #close()} method
2317     */
2318    public Appendable out() {
2319        ensureOpen();
2320        return a;
2321    }
2322
2323    /**
2324     * Returns the result of invoking {@code toString()} on the destination
2325     * for the output.  For example, the following code formats text into a
2326     * {@link StringBuilder} then retrieves the resultant string:
2327     *
2328     * <blockquote><pre>
2329     *   Formatter f = new Formatter();
2330     *   f.format("Last reboot at %tc", lastRebootDate);
2331     *   String s = f.toString();
2332     *   // -&gt; s == "Last reboot at Sat Jan 01 00:00:00 PST 2000"
2333     * </pre></blockquote>
2334     *
2335     * <p> An invocation of this method behaves in exactly the same way as the
2336     * invocation
2337     *
2338     * <pre>
2339     *     out().toString() </pre>
2340     *
2341     * <p> Depending on the specification of {@code toString} for the {@link
2342     * Appendable}, the returned string may or may not contain the characters
2343     * written to the destination.  For instance, buffers typically return
2344     * their contents in {@code toString()}, but streams cannot since the
2345     * data is discarded.
2346     *
2347     * @return  The result of invoking {@code toString()} on the destination
2348     *          for the output
2349     *
2350     * @throws  FormatterClosedException
2351     *          If this formatter has been closed by invoking its {@link
2352     *          #close()} method
2353     */
2354    public String toString() {
2355        ensureOpen();
2356        return a.toString();
2357    }
2358
2359    /**
2360     * Flushes this formatter.  If the destination implements the {@link
2361     * java.io.Flushable} interface, its {@code flush} method will be invoked.
2362     *
2363     * <p> Flushing a formatter writes any buffered output in the destination
2364     * to the underlying stream.
2365     *
2366     * @throws  FormatterClosedException
2367     *          If this formatter has been closed by invoking its {@link
2368     *          #close()} method
2369     */
2370    public void flush() {
2371        ensureOpen();
2372        if (a instanceof Flushable) {
2373            try {
2374                ((Flushable)a).flush();
2375            } catch (IOException ioe) {
2376                lastException = ioe;
2377            }
2378        }
2379    }
2380
2381    /**
2382     * Closes this formatter.  If the destination implements the {@link
2383     * java.io.Closeable} interface, its {@code close} method will be invoked.
2384     *
2385     * <p> Closing a formatter allows it to release resources it may be holding
2386     * (such as open files).  If the formatter is already closed, then invoking
2387     * this method has no effect.
2388     *
2389     * <p> Attempting to invoke any methods except {@link #ioException()} in
2390     * this formatter after it has been closed will result in a {@link
2391     * FormatterClosedException}.
2392     */
2393    public void close() {
2394        if (a == null)
2395            return;
2396        try {
2397            if (a instanceof Closeable)
2398                ((Closeable)a).close();
2399        } catch (IOException ioe) {
2400            lastException = ioe;
2401        } finally {
2402            a = null;
2403        }
2404    }
2405
2406    private void ensureOpen() {
2407        if (a == null)
2408            throw new FormatterClosedException();
2409    }
2410
2411    /**
2412     * Returns the {@code IOException} last thrown by this formatter's {@link
2413     * Appendable}.
2414     *
2415     * <p> If the destination's {@code append()} method never throws
2416     * {@code IOException}, then this method will always return {@code null}.
2417     *
2418     * @return  The last exception thrown by the Appendable or {@code null} if
2419     *          no such exception exists.
2420     */
2421    public IOException ioException() {
2422        return lastException;
2423    }
2424
2425    /**
2426     * Writes a formatted string to this object's destination using the
2427     * specified format string and arguments.  The locale used is the one
2428     * defined during the construction of this formatter.
2429     *
2430     * @param  format
2431     *         A format string as described in <a href="#syntax">Format string
2432     *         syntax</a>.
2433     *
2434     * @param  args
2435     *         Arguments referenced by the format specifiers in the format
2436     *         string.  If there are more arguments than format specifiers, the
2437     *         extra arguments are ignored.  The maximum number of arguments is
2438     *         limited by the maximum dimension of a Java array as defined by
2439     *         <cite>The Java&trade; Virtual Machine Specification</cite>.
2440     *
2441     * @throws  IllegalFormatException
2442     *          If a format string contains an illegal syntax, a format
2443     *          specifier that is incompatible with the given arguments,
2444     *          insufficient arguments given the format string, or other
2445     *          illegal conditions.  For specification of all possible
2446     *          formatting errors, see the <a href="#detail">Details</a>
2447     *          section of the formatter class specification.
2448     *
2449     * @throws  FormatterClosedException
2450     *          If this formatter has been closed by invoking its {@link
2451     *          #close()} method
2452     *
2453     * @return  This formatter
2454     */
2455    public Formatter format(String format, Object ... args) {
2456        return format(l, format, args);
2457    }
2458
2459    /**
2460     * Writes a formatted string to this object's destination using the
2461     * specified locale, format string, and arguments.
2462     *
2463     * @param  l
2464     *         The {@linkplain java.util.Locale locale} to apply during
2465     *         formatting.  If {@code l} is {@code null} then no localization
2466     *         is applied.  This does not change this object's locale that was
2467     *         set during construction.
2468     *
2469     * @param  format
2470     *         A format string as described in <a href="#syntax">Format string
2471     *         syntax</a>
2472     *
2473     * @param  args
2474     *         Arguments referenced by the format specifiers in the format
2475     *         string.  If there are more arguments than format specifiers, the
2476     *         extra arguments are ignored.  The maximum number of arguments is
2477     *         limited by the maximum dimension of a Java array as defined by
2478     *         <cite>The Java&trade; Virtual Machine Specification</cite>.
2479     *
2480     * @throws  IllegalFormatException
2481     *          If a format string contains an illegal syntax, a format
2482     *          specifier that is incompatible with the given arguments,
2483     *          insufficient arguments given the format string, or other
2484     *          illegal conditions.  For specification of all possible
2485     *          formatting errors, see the <a href="#detail">Details</a>
2486     *          section of the formatter class specification.
2487     *
2488     * @throws  FormatterClosedException
2489     *          If this formatter has been closed by invoking its {@link
2490     *          #close()} method
2491     *
2492     * @return  This formatter
2493     */
2494    public Formatter format(Locale l, String format, Object ... args) {
2495        ensureOpen();
2496
2497        // index of last argument referenced
2498        int last = -1;
2499        // last ordinary index
2500        int lasto = -1;
2501
2502        List<FormatString> fsa = parse(format);
2503        for (FormatString fs : fsa) {
2504            int index = fs.index();
2505            try {
2506                switch (index) {
2507                case -2:  // fixed string, "%n", or "%%"
2508                    fs.print(null, l);
2509                    break;
2510                case -1:  // relative index
2511                    if (last < 0 || (args != null && last > args.length - 1))
2512                        throw new MissingFormatArgumentException(fs.toString());
2513                    fs.print((args == null ? null : args[last]), l);
2514                    break;
2515                case 0:  // ordinary index
2516                    lasto++;
2517                    last = lasto;
2518                    if (args != null && lasto > args.length - 1)
2519                        throw new MissingFormatArgumentException(fs.toString());
2520                    fs.print((args == null ? null : args[lasto]), l);
2521                    break;
2522                default:  // explicit index
2523                    last = index - 1;
2524                    if (args != null && last > args.length - 1)
2525                        throw new MissingFormatArgumentException(fs.toString());
2526                    fs.print((args == null ? null : args[last]), l);
2527                    break;
2528                }
2529            } catch (IOException x) {
2530                lastException = x;
2531            }
2532        }
2533        return this;
2534    }
2535
2536    // %[argument_index$][flags][width][.precision][t]conversion
2537    private static final String formatSpecifier
2538        = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
2539
2540    private static Pattern fsPattern = Pattern.compile(formatSpecifier);
2541
2542    /**
2543     * Finds format specifiers in the format string.
2544     */
2545    private List<FormatString> parse(String s) {
2546        ArrayList<FormatString> al = new ArrayList<>();
2547        Matcher m = fsPattern.matcher(s);
2548        for (int i = 0, len = s.length(); i < len; ) {
2549            if (m.find(i)) {
2550                // Anything between the start of the string and the beginning
2551                // of the format specifier is either fixed text or contains
2552                // an invalid format string.
2553                if (m.start() != i) {
2554                    // Make sure we didn't miss any invalid format specifiers
2555                    checkText(s, i, m.start());
2556                    // Assume previous characters were fixed text
2557                    al.add(new FixedString(s, i, m.start()));
2558                }
2559
2560                al.add(new FormatSpecifier(s, m));
2561                i = m.end();
2562            } else {
2563                // No more valid format specifiers.  Check for possible invalid
2564                // format specifiers.
2565                checkText(s, i, len);
2566                // The rest of the string is fixed text
2567                al.add(new FixedString(s, i, s.length()));
2568                break;
2569            }
2570        }
2571        return al;
2572    }
2573
2574    private static void checkText(String s, int start, int end) {
2575        for (int i = start; i < end; i++) {
2576            // Any '%' found in the region starts an invalid format specifier.
2577            if (s.charAt(i) == '%') {
2578                char c = (i == end - 1) ? '%' : s.charAt(i + 1);
2579                throw new UnknownFormatConversionException(String.valueOf(c));
2580            }
2581        }
2582    }
2583
2584    private interface FormatString {
2585        int index();
2586        void print(Object arg, Locale l) throws IOException;
2587        String toString();
2588    }
2589
2590    private class FixedString implements FormatString {
2591        private String s;
2592        private int start;
2593        private int end;
2594        FixedString(String s, int start, int end) {
2595            this.s = s;
2596            this.start = start;
2597            this.end = end;
2598        }
2599        public int index() { return -2; }
2600        public void print(Object arg, Locale l)
2601            throws IOException { a.append(s, start, end); }
2602        public String toString() { return s.substring(start, end); }
2603    }
2604
2605    /**
2606     * Enum for {@code BigDecimal} formatting.
2607     */
2608    public enum BigDecimalLayoutForm {
2609        /**
2610         * Format the {@code BigDecimal} in computerized scientific notation.
2611         */
2612        SCIENTIFIC,
2613
2614        /**
2615         * Format the {@code BigDecimal} as a decimal number.
2616         */
2617        DECIMAL_FLOAT
2618    };
2619
2620    private class FormatSpecifier implements FormatString {
2621        private int index = -1;
2622        private Flags f = Flags.NONE;
2623        private int width;
2624        private int precision;
2625        private boolean dt = false;
2626        private char c;
2627
2628        private int index(String s, int start, int end) {
2629            if (start >= 0) {
2630                try {
2631                    // skip the trailing '$'
2632                    index = Integer.parseInt(s, start, end - 1, 10);
2633                } catch (NumberFormatException x) {
2634                    assert(false);
2635                }
2636            } else {
2637                index = 0;
2638            }
2639            return index;
2640        }
2641
2642        public int index() {
2643            return index;
2644        }
2645
2646        private Flags flags(String s, int start, int end) {
2647            f = Flags.parse(s, start, end);
2648            if (f.contains(Flags.PREVIOUS))
2649                index = -1;
2650            return f;
2651        }
2652
2653        private int width(String s, int start, int end) {
2654            width = -1;
2655            if (start >= 0) {
2656                try {
2657                    width = Integer.parseInt(s, start, end, 10);
2658                    if (width < 0)
2659                        throw new IllegalFormatWidthException(width);
2660                } catch (NumberFormatException x) {
2661                    assert(false);
2662                }
2663            }
2664            return width;
2665        }
2666
2667        private int precision(String s, int start, int end) {
2668            precision = -1;
2669            if (start >= 0) {
2670                try {
2671                    // skip the leading '.'
2672                    precision = Integer.parseInt(s, start + 1, end, 10);
2673                    if (precision < 0)
2674                        throw new IllegalFormatPrecisionException(precision);
2675                } catch (NumberFormatException x) {
2676                    assert(false);
2677                }
2678            }
2679            return precision;
2680        }
2681
2682        private char conversion(char conv) {
2683            c = conv;
2684            if (!dt) {
2685                if (!Conversion.isValid(c)) {
2686                    throw new UnknownFormatConversionException(String.valueOf(c));
2687                }
2688                if (Character.isUpperCase(c)) {
2689                    f.add(Flags.UPPERCASE);
2690                    c = Character.toLowerCase(c);
2691                }
2692                if (Conversion.isText(c)) {
2693                    index = -2;
2694                }
2695            }
2696            return c;
2697        }
2698
2699        FormatSpecifier(String s, Matcher m) {
2700            index(s, m.start(1), m.end(1));
2701            flags(s, m.start(2), m.end(2));
2702            width(s, m.start(3), m.end(3));
2703            precision(s, m.start(4), m.end(4));
2704
2705            int tTStart = m.start(5);
2706            if (tTStart >= 0) {
2707                dt = true;
2708                if (s.charAt(tTStart) == 'T') {
2709                    f.add(Flags.UPPERCASE);
2710                }
2711            }
2712            conversion(s.charAt(m.start(6)));
2713
2714            if (dt)
2715                checkDateTime();
2716            else if (Conversion.isGeneral(c))
2717                checkGeneral();
2718            else if (Conversion.isCharacter(c))
2719                checkCharacter();
2720            else if (Conversion.isInteger(c))
2721                checkInteger();
2722            else if (Conversion.isFloat(c))
2723                checkFloat();
2724            else if (Conversion.isText(c))
2725                checkText();
2726            else
2727                throw new UnknownFormatConversionException(String.valueOf(c));
2728        }
2729
2730        public void print(Object arg, Locale l) throws IOException {
2731            if (dt) {
2732                printDateTime(arg, l);
2733                return;
2734            }
2735            switch(c) {
2736            case Conversion.DECIMAL_INTEGER:
2737            case Conversion.OCTAL_INTEGER:
2738            case Conversion.HEXADECIMAL_INTEGER:
2739                printInteger(arg, l);
2740                break;
2741            case Conversion.SCIENTIFIC:
2742            case Conversion.GENERAL:
2743            case Conversion.DECIMAL_FLOAT:
2744            case Conversion.HEXADECIMAL_FLOAT:
2745                printFloat(arg, l);
2746                break;
2747            case Conversion.CHARACTER:
2748            case Conversion.CHARACTER_UPPER:
2749                printCharacter(arg);
2750                break;
2751            case Conversion.BOOLEAN:
2752                printBoolean(arg);
2753                break;
2754            case Conversion.STRING:
2755                printString(arg, l);
2756                break;
2757            case Conversion.HASHCODE:
2758                printHashCode(arg);
2759                break;
2760            case Conversion.LINE_SEPARATOR:
2761                a.append(System.lineSeparator());
2762                break;
2763            case Conversion.PERCENT_SIGN:
2764                a.append('%');
2765                break;
2766            default:
2767                assert false;
2768            }
2769        }
2770
2771        private void printInteger(Object arg, Locale l) throws IOException {
2772            if (arg == null)
2773                print("null");
2774            else if (arg instanceof Byte)
2775                print(((Byte)arg).byteValue(), l);
2776            else if (arg instanceof Short)
2777                print(((Short)arg).shortValue(), l);
2778            else if (arg instanceof Integer)
2779                print(((Integer)arg).intValue(), l);
2780            else if (arg instanceof Long)
2781                print(((Long)arg).longValue(), l);
2782            else if (arg instanceof BigInteger)
2783                print(((BigInteger)arg), l);
2784            else
2785                failConversion(c, arg);
2786        }
2787
2788        private void printFloat(Object arg, Locale l) throws IOException {
2789            if (arg == null)
2790                print("null");
2791            else if (arg instanceof Float)
2792                print(((Float)arg).floatValue(), l);
2793            else if (arg instanceof Double)
2794                print(((Double)arg).doubleValue(), l);
2795            else if (arg instanceof BigDecimal)
2796                print(((BigDecimal)arg), l);
2797            else
2798                failConversion(c, arg);
2799        }
2800
2801        private void printDateTime(Object arg, Locale l) throws IOException {
2802            if (arg == null) {
2803                print("null");
2804                return;
2805            }
2806            Calendar cal = null;
2807
2808            // Instead of Calendar.setLenient(true), perhaps we should
2809            // wrap the IllegalArgumentException that might be thrown?
2810            if (arg instanceof Long) {
2811                // Note that the following method uses an instance of the
2812                // default time zone (TimeZone.getDefaultRef().
2813                cal = Calendar.getInstance(l == null ? Locale.US : l);
2814                cal.setTimeInMillis((Long)arg);
2815            } else if (arg instanceof Date) {
2816                // Note that the following method uses an instance of the
2817                // default time zone (TimeZone.getDefaultRef().
2818                cal = Calendar.getInstance(l == null ? Locale.US : l);
2819                cal.setTime((Date)arg);
2820            } else if (arg instanceof Calendar) {
2821                cal = (Calendar) ((Calendar) arg).clone();
2822                cal.setLenient(true);
2823            } else if (arg instanceof TemporalAccessor) {
2824                print((TemporalAccessor) arg, c, l);
2825                return;
2826            } else {
2827                failConversion(c, arg);
2828            }
2829            // Use the provided locale so that invocations of
2830            // localizedMagnitude() use optimizations for null.
2831            print(cal, c, l);
2832        }
2833
2834        private void printCharacter(Object arg) throws IOException {
2835            if (arg == null) {
2836                print("null");
2837                return;
2838            }
2839            String s = null;
2840            if (arg instanceof Character) {
2841                s = ((Character)arg).toString();
2842            } else if (arg instanceof Byte) {
2843                byte i = ((Byte)arg).byteValue();
2844                if (Character.isValidCodePoint(i))
2845                    s = new String(Character.toChars(i));
2846                else
2847                    throw new IllegalFormatCodePointException(i);
2848            } else if (arg instanceof Short) {
2849                short i = ((Short)arg).shortValue();
2850                if (Character.isValidCodePoint(i))
2851                    s = new String(Character.toChars(i));
2852                else
2853                    throw new IllegalFormatCodePointException(i);
2854            } else if (arg instanceof Integer) {
2855                int i = ((Integer)arg).intValue();
2856                if (Character.isValidCodePoint(i))
2857                    s = new String(Character.toChars(i));
2858                else
2859                    throw new IllegalFormatCodePointException(i);
2860            } else {
2861                failConversion(c, arg);
2862            }
2863            print(s);
2864        }
2865
2866        private void printString(Object arg, Locale l) throws IOException {
2867            if (arg instanceof Formattable) {
2868                Formatter fmt = Formatter.this;
2869                if (fmt.locale() != l)
2870                    fmt = new Formatter(fmt.out(), l);
2871                ((Formattable)arg).formatTo(fmt, f.valueOf(), width, precision);
2872            } else {
2873                if (f.contains(Flags.ALTERNATE))
2874                    failMismatch(Flags.ALTERNATE, 's');
2875                if (arg == null)
2876                    print("null");
2877                else
2878                    print(arg.toString());
2879            }
2880        }
2881
2882        private void printBoolean(Object arg) throws IOException {
2883            String s;
2884            if (arg != null)
2885                s = ((arg instanceof Boolean)
2886                     ? ((Boolean)arg).toString()
2887                     : Boolean.toString(true));
2888            else
2889                s = Boolean.toString(false);
2890            print(s);
2891        }
2892
2893        private void printHashCode(Object arg) throws IOException {
2894            String s = (arg == null
2895                        ? "null"
2896                        : Integer.toHexString(arg.hashCode()));
2897            print(s);
2898        }
2899
2900        private void print(String s) throws IOException {
2901            if (precision != -1 && precision < s.length())
2902                s = s.substring(0, precision);
2903            if (f.contains(Flags.UPPERCASE))
2904                s = s.toUpperCase();
2905            appendJustified(a, s);
2906        }
2907
2908        private Appendable appendJustified(Appendable a, CharSequence cs) throws IOException {
2909             if (width == -1) {
2910                 return a.append(cs);
2911             }
2912             boolean padRight = f.contains(Flags.LEFT_JUSTIFY);
2913             int sp = width - cs.length();
2914             if (padRight) {
2915                 a.append(cs);
2916             }
2917             for (int i = 0; i < sp; i++) {
2918                 a.append(' ');
2919             }
2920             if (!padRight) {
2921                 a.append(cs);
2922             }
2923             return a;
2924        }
2925
2926        public String toString() {
2927            StringBuilder sb = new StringBuilder("%");
2928            // Flags.UPPERCASE is set internally for legal conversions.
2929            Flags dupf = f.dup().remove(Flags.UPPERCASE);
2930            sb.append(dupf.toString());
2931            if (index > 0)
2932                sb.append(index).append('$');
2933            if (width != -1)
2934                sb.append(width);
2935            if (precision != -1)
2936                sb.append('.').append(precision);
2937            if (dt)
2938                sb.append(f.contains(Flags.UPPERCASE) ? 'T' : 't');
2939            sb.append(f.contains(Flags.UPPERCASE)
2940                      ? Character.toUpperCase(c) : c);
2941            return sb.toString();
2942        }
2943
2944        private void checkGeneral() {
2945            if ((c == Conversion.BOOLEAN || c == Conversion.HASHCODE)
2946                && f.contains(Flags.ALTERNATE))
2947                failMismatch(Flags.ALTERNATE, c);
2948            // '-' requires a width
2949            if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))
2950                throw new MissingFormatWidthException(toString());
2951            checkBadFlags(Flags.PLUS, Flags.LEADING_SPACE, Flags.ZERO_PAD,
2952                          Flags.GROUP, Flags.PARENTHESES);
2953        }
2954
2955        private void checkDateTime() {
2956            if (precision != -1)
2957                throw new IllegalFormatPrecisionException(precision);
2958            if (!DateTime.isValid(c))
2959                throw new UnknownFormatConversionException("t" + c);
2960            checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE,
2961                          Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES);
2962            // '-' requires a width
2963            if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))
2964                throw new MissingFormatWidthException(toString());
2965        }
2966
2967        private void checkCharacter() {
2968            if (precision != -1)
2969                throw new IllegalFormatPrecisionException(precision);
2970            checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE,
2971                          Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES);
2972            // '-' requires a width
2973            if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))
2974                throw new MissingFormatWidthException(toString());
2975        }
2976
2977        private void checkInteger() {
2978            checkNumeric();
2979            if (precision != -1)
2980                throw new IllegalFormatPrecisionException(precision);
2981
2982            if (c == Conversion.DECIMAL_INTEGER)
2983                checkBadFlags(Flags.ALTERNATE);
2984            else if (c == Conversion.OCTAL_INTEGER)
2985                checkBadFlags(Flags.GROUP);
2986            else
2987                checkBadFlags(Flags.GROUP);
2988        }
2989
2990        private void checkBadFlags(Flags ... badFlags) {
2991            for (Flags badFlag : badFlags)
2992                if (f.contains(badFlag))
2993                    failMismatch(badFlag, c);
2994        }
2995
2996        private void checkFloat() {
2997            checkNumeric();
2998            if (c == Conversion.DECIMAL_FLOAT) {
2999            } else if (c == Conversion.HEXADECIMAL_FLOAT) {
3000                checkBadFlags(Flags.PARENTHESES, Flags.GROUP);
3001            } else if (c == Conversion.SCIENTIFIC) {
3002                checkBadFlags(Flags.GROUP);
3003            } else if (c == Conversion.GENERAL) {
3004                checkBadFlags(Flags.ALTERNATE);
3005            }
3006        }
3007
3008        private void checkNumeric() {
3009            if (width != -1 && width < 0)
3010                throw new IllegalFormatWidthException(width);
3011
3012            if (precision != -1 && precision < 0)
3013                throw new IllegalFormatPrecisionException(precision);
3014
3015            // '-' and '0' require a width
3016            if (width == -1
3017                && (f.contains(Flags.LEFT_JUSTIFY) || f.contains(Flags.ZERO_PAD)))
3018                throw new MissingFormatWidthException(toString());
3019
3020            // bad combination
3021            if ((f.contains(Flags.PLUS) && f.contains(Flags.LEADING_SPACE))
3022                || (f.contains(Flags.LEFT_JUSTIFY) && f.contains(Flags.ZERO_PAD)))
3023                throw new IllegalFormatFlagsException(f.toString());
3024        }
3025
3026        private void checkText() {
3027            if (precision != -1)
3028                throw new IllegalFormatPrecisionException(precision);
3029            switch (c) {
3030            case Conversion.PERCENT_SIGN:
3031                if (f.valueOf() != Flags.LEFT_JUSTIFY.valueOf()
3032                    && f.valueOf() != Flags.NONE.valueOf())
3033                    throw new IllegalFormatFlagsException(f.toString());
3034                // '-' requires a width
3035                if (width == -1 && f.contains(Flags.LEFT_JUSTIFY))
3036                    throw new MissingFormatWidthException(toString());
3037                break;
3038            case Conversion.LINE_SEPARATOR:
3039                if (width != -1)
3040                    throw new IllegalFormatWidthException(width);
3041                if (f.valueOf() != Flags.NONE.valueOf())
3042                    throw new IllegalFormatFlagsException(f.toString());
3043                break;
3044            default:
3045                assert false;
3046            }
3047        }
3048
3049        private void print(byte value, Locale l) throws IOException {
3050            long v = value;
3051            if (value < 0
3052                && (c == Conversion.OCTAL_INTEGER
3053                    || c == Conversion.HEXADECIMAL_INTEGER)) {
3054                v += (1L << 8);
3055                assert v >= 0 : v;
3056            }
3057            print(v, l);
3058        }
3059
3060        private void print(short value, Locale l) throws IOException {
3061            long v = value;
3062            if (value < 0
3063                && (c == Conversion.OCTAL_INTEGER
3064                    || c == Conversion.HEXADECIMAL_INTEGER)) {
3065                v += (1L << 16);
3066                assert v >= 0 : v;
3067            }
3068            print(v, l);
3069        }
3070
3071        private void print(int value, Locale l) throws IOException {
3072            long v = value;
3073            if (value < 0
3074                && (c == Conversion.OCTAL_INTEGER
3075                    || c == Conversion.HEXADECIMAL_INTEGER)) {
3076                v += (1L << 32);
3077                assert v >= 0 : v;
3078            }
3079            print(v, l);
3080        }
3081
3082        private void print(long value, Locale l) throws IOException {
3083
3084            StringBuilder sb = new StringBuilder();
3085
3086            if (c == Conversion.DECIMAL_INTEGER) {
3087                boolean neg = value < 0;
3088                String valueStr = Long.toString(value, 10);
3089
3090                // leading sign indicator
3091                leadingSign(sb, neg);
3092
3093                // the value
3094                localizedMagnitude(sb, valueStr, neg ? 1 : 0, f, adjustWidth(width, f, neg), l);
3095
3096                // trailing sign indicator
3097                trailingSign(sb, neg);
3098            } else if (c == Conversion.OCTAL_INTEGER) {
3099                checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE,
3100                              Flags.PLUS);
3101                String s = Long.toOctalString(value);
3102                int len = (f.contains(Flags.ALTERNATE)
3103                           ? s.length() + 1
3104                           : s.length());
3105
3106                // apply ALTERNATE (radix indicator for octal) before ZERO_PAD
3107                if (f.contains(Flags.ALTERNATE))
3108                    sb.append('0');
3109                if (f.contains(Flags.ZERO_PAD)) {
3110                    trailingZeros(sb, width - len);
3111                }
3112                sb.append(s);
3113            } else if (c == Conversion.HEXADECIMAL_INTEGER) {
3114                checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE,
3115                              Flags.PLUS);
3116                String s = Long.toHexString(value);
3117                int len = (f.contains(Flags.ALTERNATE)
3118                           ? s.length() + 2
3119                           : s.length());
3120
3121                // apply ALTERNATE (radix indicator for hex) before ZERO_PAD
3122                if (f.contains(Flags.ALTERNATE))
3123                    sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x");
3124                if (f.contains(Flags.ZERO_PAD)) {
3125                    trailingZeros(sb, width - len);
3126                }
3127                if (f.contains(Flags.UPPERCASE))
3128                    s = s.toUpperCase();
3129                sb.append(s);
3130            }
3131
3132            // justify based on width
3133            appendJustified(a, sb);
3134        }
3135
3136        // neg := val < 0
3137        private StringBuilder leadingSign(StringBuilder sb, boolean neg) {
3138            if (!neg) {
3139                if (f.contains(Flags.PLUS)) {
3140                    sb.append('+');
3141                } else if (f.contains(Flags.LEADING_SPACE)) {
3142                    sb.append(' ');
3143                }
3144            } else {
3145                if (f.contains(Flags.PARENTHESES))
3146                    sb.append('(');
3147                else
3148                    sb.append('-');
3149            }
3150            return sb;
3151        }
3152
3153        // neg := val < 0
3154        private StringBuilder trailingSign(StringBuilder sb, boolean neg) {
3155            if (neg && f.contains(Flags.PARENTHESES))
3156                sb.append(')');
3157            return sb;
3158        }
3159
3160        private void print(BigInteger value, Locale l) throws IOException {
3161            StringBuilder sb = new StringBuilder();
3162            boolean neg = value.signum() == -1;
3163            BigInteger v = value.abs();
3164
3165            // leading sign indicator
3166            leadingSign(sb, neg);
3167
3168            // the value
3169            if (c == Conversion.DECIMAL_INTEGER) {
3170                localizedMagnitude(sb, v.toString(), 0, f, adjustWidth(width, f, neg), l);
3171            } else if (c == Conversion.OCTAL_INTEGER) {
3172                String s = v.toString(8);
3173
3174                int len = s.length() + sb.length();
3175                if (neg && f.contains(Flags.PARENTHESES))
3176                    len++;
3177
3178                // apply ALTERNATE (radix indicator for octal) before ZERO_PAD
3179                if (f.contains(Flags.ALTERNATE)) {
3180                    len++;
3181                    sb.append('0');
3182                }
3183                if (f.contains(Flags.ZERO_PAD)) {
3184                    trailingZeros(sb, width - len);
3185                }
3186                sb.append(s);
3187            } else if (c == Conversion.HEXADECIMAL_INTEGER) {
3188                String s = v.toString(16);
3189
3190                int len = s.length() + sb.length();
3191                if (neg && f.contains(Flags.PARENTHESES))
3192                    len++;
3193
3194                // apply ALTERNATE (radix indicator for hex) before ZERO_PAD
3195                if (f.contains(Flags.ALTERNATE)) {
3196                    len += 2;
3197                    sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x");
3198                }
3199                if (f.contains(Flags.ZERO_PAD)) {
3200                    trailingZeros(sb, width - len);
3201                }
3202                if (f.contains(Flags.UPPERCASE))
3203                    s = s.toUpperCase();
3204                sb.append(s);
3205            }
3206
3207            // trailing sign indicator
3208            trailingSign(sb, (value.signum() == -1));
3209
3210            // justify based on width
3211            appendJustified(a, sb);
3212        }
3213
3214        private void print(float value, Locale l) throws IOException {
3215            print((double) value, l);
3216        }
3217
3218        private void print(double value, Locale l) throws IOException {
3219            StringBuilder sb = new StringBuilder();
3220            boolean neg = Double.compare(value, 0.0) == -1;
3221
3222            if (!Double.isNaN(value)) {
3223                double v = Math.abs(value);
3224
3225                // leading sign indicator
3226                leadingSign(sb, neg);
3227
3228                // the value
3229                if (!Double.isInfinite(v))
3230                    print(sb, v, l, f, c, precision, neg);
3231                else
3232                    sb.append(f.contains(Flags.UPPERCASE)
3233                              ? "INFINITY" : "Infinity");
3234
3235                // trailing sign indicator
3236                trailingSign(sb, neg);
3237            } else {
3238                sb.append(f.contains(Flags.UPPERCASE) ? "NAN" : "NaN");
3239            }
3240
3241            // justify based on width
3242            appendJustified(a, sb);
3243        }
3244
3245        // !Double.isInfinite(value) && !Double.isNaN(value)
3246        private void print(StringBuilder sb, double value, Locale l,
3247                           Flags f, char c, int precision, boolean neg)
3248            throws IOException
3249        {
3250            if (c == Conversion.SCIENTIFIC) {
3251                // Create a new FormattedFloatingDecimal with the desired
3252                // precision.
3253                int prec = (precision == -1 ? 6 : precision);
3254
3255                FormattedFloatingDecimal fd
3256                        = FormattedFloatingDecimal.valueOf(value, prec,
3257                          FormattedFloatingDecimal.Form.SCIENTIFIC);
3258
3259                StringBuilder mant = new StringBuilder().append(fd.getMantissa());
3260                addZeros(mant, prec);
3261
3262                // If the precision is zero and the '#' flag is set, add the
3263                // requested decimal point.
3264                if (f.contains(Flags.ALTERNATE) && (prec == 0)) {
3265                    mant.append('.');
3266                }
3267
3268                char[] exp = (value == 0.0)
3269                    ? new char[] {'+','0','0'} : fd.getExponent();
3270
3271                int newW = width;
3272                if (width != -1) {
3273                    newW = adjustWidth(width - exp.length - 1, f, neg);
3274                }
3275                localizedMagnitude(sb, mant, 0, f, newW, l);
3276
3277                sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');
3278
3279                char sign = exp[0];
3280                assert(sign == '+' || sign == '-');
3281                sb.append(sign);
3282
3283                localizedMagnitudeExp(sb, exp, 1, l);
3284            } else if (c == Conversion.DECIMAL_FLOAT) {
3285                // Create a new FormattedFloatingDecimal with the desired
3286                // precision.
3287                int prec = (precision == -1 ? 6 : precision);
3288
3289                FormattedFloatingDecimal fd
3290                        = FormattedFloatingDecimal.valueOf(value, prec,
3291                          FormattedFloatingDecimal.Form.DECIMAL_FLOAT);
3292
3293                StringBuilder mant = new StringBuilder().append(fd.getMantissa());
3294                addZeros(mant, prec);
3295
3296                // If the precision is zero and the '#' flag is set, add the
3297                // requested decimal point.
3298                if (f.contains(Flags.ALTERNATE) && (prec == 0))
3299                    mant.append('.');
3300
3301                int newW = width;
3302                if (width != -1)
3303                    newW = adjustWidth(width, f, neg);
3304                localizedMagnitude(sb, mant, 0, f, newW, l);
3305            } else if (c == Conversion.GENERAL) {
3306                int prec = precision;
3307                if (precision == -1)
3308                    prec = 6;
3309                else if (precision == 0)
3310                    prec = 1;
3311
3312                char[] exp;
3313                StringBuilder mant = new StringBuilder();
3314                int expRounded;
3315                if (value == 0.0) {
3316                    exp = null;
3317                    mant.append('0');
3318                    expRounded = 0;
3319                } else {
3320                    FormattedFloatingDecimal fd
3321                        = FormattedFloatingDecimal.valueOf(value, prec,
3322                          FormattedFloatingDecimal.Form.GENERAL);
3323                    exp = fd.getExponent();
3324                    mant.append(fd.getMantissa());
3325                    expRounded = fd.getExponentRounded();
3326                }
3327
3328                if (exp != null) {
3329                    prec -= 1;
3330                } else {
3331                    prec -= expRounded + 1;
3332                }
3333
3334                addZeros(mant, prec);
3335                // If the precision is zero and the '#' flag is set, add the
3336                // requested decimal point.
3337                if (f.contains(Flags.ALTERNATE) && (prec == 0)) {
3338                    mant.append('.');
3339                }
3340
3341                int newW = width;
3342                if (width != -1) {
3343                    if (exp != null)
3344                        newW = adjustWidth(width - exp.length - 1, f, neg);
3345                    else
3346                        newW = adjustWidth(width, f, neg);
3347                }
3348                localizedMagnitude(sb, mant, 0, f, newW, l);
3349
3350                if (exp != null) {
3351                    sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');
3352
3353                    char sign = exp[0];
3354                    assert(sign == '+' || sign == '-');
3355                    sb.append(sign);
3356
3357                    localizedMagnitudeExp(sb, exp, 1, l);
3358                }
3359            } else if (c == Conversion.HEXADECIMAL_FLOAT) {
3360                int prec = precision;
3361                if (precision == -1)
3362                    // assume that we want all of the digits
3363                    prec = 0;
3364                else if (precision == 0)
3365                    prec = 1;
3366
3367                String s = hexDouble(value, prec);
3368
3369                StringBuilder va = new StringBuilder();
3370                boolean upper = f.contains(Flags.UPPERCASE);
3371                sb.append(upper ? "0X" : "0x");
3372
3373                if (f.contains(Flags.ZERO_PAD)) {
3374                    trailingZeros(sb, width - s.length() - 2);
3375                }
3376
3377                int idx = s.indexOf('p');
3378                if (upper) {
3379                    String tmp = s.substring(0, idx);
3380                    // don't localize hex
3381                    tmp = tmp.toUpperCase(Locale.US);
3382                    va.append(tmp);
3383                } else {
3384                    va.append(s, 0, idx);
3385                }
3386                if (prec != 0) {
3387                    addZeros(va, prec);
3388                }
3389                sb.append(va);
3390                sb.append(upper ? 'P' : 'p');
3391                sb.append(s, idx+1, s.length());
3392            }
3393        }
3394
3395        // Add zeros to the requested precision.
3396        private void addZeros(StringBuilder sb, int prec) {
3397            // Look for the dot.  If we don't find one, the we'll need to add
3398            // it before we add the zeros.
3399            int len = sb.length();
3400            int i;
3401            for (i = 0; i < len; i++) {
3402                if (sb.charAt(i) == '.') {
3403                    break;
3404                }
3405            }
3406            boolean needDot = false;
3407            if (i == len) {
3408                needDot = true;
3409            }
3410
3411            // Determine existing precision.
3412            int outPrec = len - i - (needDot ? 0 : 1);
3413            assert (outPrec <= prec);
3414            if (outPrec == prec) {
3415                return;
3416            }
3417
3418            // Add dot if previously determined to be necessary.
3419            if (needDot) {
3420                sb.append('.');
3421            }
3422
3423            // Add zeros.
3424            trailingZeros(sb, prec - outPrec);
3425        }
3426
3427        // Method assumes that d > 0.
3428        private String hexDouble(double d, int prec) {
3429            // Let Double.toHexString handle simple cases
3430            if (!Double.isFinite(d) || d == 0.0 || prec == 0 || prec >= 13) {
3431                // remove "0x"
3432                return Double.toHexString(d).substring(2);
3433            } else {
3434                assert(prec >= 1 && prec <= 12);
3435
3436                int exponent  = Math.getExponent(d);
3437                boolean subnormal
3438                    = (exponent == DoubleConsts.MIN_EXPONENT - 1);
3439
3440                // If this is subnormal input so normalize (could be faster to
3441                // do as integer operation).
3442                if (subnormal) {
3443                    scaleUp = Math.scalb(1.0, 54);
3444                    d *= scaleUp;
3445                    // Calculate the exponent.  This is not just exponent + 54
3446                    // since the former is not the normalized exponent.
3447                    exponent = Math.getExponent(d);
3448                    assert exponent >= DoubleConsts.MIN_EXPONENT &&
3449                        exponent <= DoubleConsts.MAX_EXPONENT: exponent;
3450                }
3451
3452                int precision = 1 + prec*4;
3453                int shiftDistance
3454                    =  DoubleConsts.SIGNIFICAND_WIDTH - precision;
3455                assert(shiftDistance >= 1 && shiftDistance < DoubleConsts.SIGNIFICAND_WIDTH);
3456
3457                long doppel = Double.doubleToLongBits(d);
3458                // Deterime the number of bits to keep.
3459                long newSignif
3460                    = (doppel & (DoubleConsts.EXP_BIT_MASK
3461                                 | DoubleConsts.SIGNIF_BIT_MASK))
3462                                     >> shiftDistance;
3463                // Bits to round away.
3464                long roundingBits = doppel & ~(~0L << shiftDistance);
3465
3466                // To decide how to round, look at the low-order bit of the
3467                // working significand, the highest order discarded bit (the
3468                // round bit) and whether any of the lower order discarded bits
3469                // are nonzero (the sticky bit).
3470
3471                boolean leastZero = (newSignif & 0x1L) == 0L;
3472                boolean round
3473                    = ((1L << (shiftDistance - 1) ) & roundingBits) != 0L;
3474                boolean sticky  = shiftDistance > 1 &&
3475                    (~(1L<< (shiftDistance - 1)) & roundingBits) != 0;
3476                if((leastZero && round && sticky) || (!leastZero && round)) {
3477                    newSignif++;
3478                }
3479
3480                long signBit = doppel & DoubleConsts.SIGN_BIT_MASK;
3481                newSignif = signBit | (newSignif << shiftDistance);
3482                double result = Double.longBitsToDouble(newSignif);
3483
3484                if (Double.isInfinite(result) ) {
3485                    // Infinite result generated by rounding
3486                    return "1.0p1024";
3487                } else {
3488                    String res = Double.toHexString(result).substring(2);
3489                    if (!subnormal)
3490                        return res;
3491                    else {
3492                        // Create a normalized subnormal string.
3493                        int idx = res.indexOf('p');
3494                        if (idx == -1) {
3495                            // No 'p' character in hex string.
3496                            assert false;
3497                            return null;
3498                        } else {
3499                            // Get exponent and append at the end.
3500                            String exp = res.substring(idx + 1);
3501                            int iexp = Integer.parseInt(exp) -54;
3502                            return res.substring(0, idx) + "p"
3503                                + Integer.toString(iexp);
3504                        }
3505                    }
3506                }
3507            }
3508        }
3509
3510        private void print(BigDecimal value, Locale l) throws IOException {
3511            if (c == Conversion.HEXADECIMAL_FLOAT)
3512                failConversion(c, value);
3513            StringBuilder sb = new StringBuilder();
3514            boolean neg = value.signum() == -1;
3515            BigDecimal v = value.abs();
3516            // leading sign indicator
3517            leadingSign(sb, neg);
3518
3519            // the value
3520            print(sb, v, l, f, c, precision, neg);
3521
3522            // trailing sign indicator
3523            trailingSign(sb, neg);
3524
3525            // justify based on width
3526            appendJustified(a, sb);
3527        }
3528
3529        // value > 0
3530        private void print(StringBuilder sb, BigDecimal value, Locale l,
3531                           Flags f, char c, int precision, boolean neg)
3532            throws IOException
3533        {
3534            if (c == Conversion.SCIENTIFIC) {
3535                // Create a new BigDecimal with the desired precision.
3536                int prec = (precision == -1 ? 6 : precision);
3537                int scale = value.scale();
3538                int origPrec = value.precision();
3539                int nzeros = 0;
3540                int compPrec;
3541
3542                if (prec > origPrec - 1) {
3543                    compPrec = origPrec;
3544                    nzeros = prec - (origPrec - 1);
3545                } else {
3546                    compPrec = prec + 1;
3547                }
3548
3549                MathContext mc = new MathContext(compPrec);
3550                BigDecimal v
3551                    = new BigDecimal(value.unscaledValue(), scale, mc);
3552
3553                BigDecimalLayout bdl
3554                    = new BigDecimalLayout(v.unscaledValue(), v.scale(),
3555                                           BigDecimalLayoutForm.SCIENTIFIC);
3556
3557                StringBuilder mant = bdl.mantissa();
3558
3559                // Add a decimal point if necessary.  The mantissa may not
3560                // contain a decimal point if the scale is zero (the internal
3561                // representation has no fractional part) or the original
3562                // precision is one. Append a decimal point if '#' is set or if
3563                // we require zero padding to get to the requested precision.
3564                if ((origPrec == 1 || !bdl.hasDot())
3565                        && (nzeros > 0 || (f.contains(Flags.ALTERNATE)))) {
3566                    mant.append('.');
3567                }
3568
3569                // Add trailing zeros in the case precision is greater than
3570                // the number of available digits after the decimal separator.
3571                trailingZeros(mant, nzeros);
3572
3573                StringBuilder exp = bdl.exponent();
3574                int newW = width;
3575                if (width != -1) {
3576                    newW = adjustWidth(width - exp.length() - 1, f, neg);
3577                }
3578                localizedMagnitude(sb, mant, 0, f, newW, l);
3579
3580                sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');
3581
3582                Flags flags = f.dup().remove(Flags.GROUP);
3583                char sign = exp.charAt(0);
3584                assert(sign == '+' || sign == '-');
3585                sb.append(sign);
3586
3587                sb.append(localizedMagnitude(null, exp, 1, flags, -1, l));
3588            } else if (c == Conversion.DECIMAL_FLOAT) {
3589                // Create a new BigDecimal with the desired precision.
3590                int prec = (precision == -1 ? 6 : precision);
3591                int scale = value.scale();
3592
3593                if (scale > prec) {
3594                    // more "scale" digits than the requested "precision"
3595                    int compPrec = value.precision();
3596                    if (compPrec <= scale) {
3597                        // case of 0.xxxxxx
3598                        value = value.setScale(prec, RoundingMode.HALF_UP);
3599                    } else {
3600                        compPrec -= (scale - prec);
3601                        value = new BigDecimal(value.unscaledValue(),
3602                                               scale,
3603                                               new MathContext(compPrec));
3604                    }
3605                }
3606                BigDecimalLayout bdl = new BigDecimalLayout(
3607                                           value.unscaledValue(),
3608                                           value.scale(),
3609                                           BigDecimalLayoutForm.DECIMAL_FLOAT);
3610
3611                StringBuilder mant = bdl.mantissa();
3612                int nzeros = (bdl.scale() < prec ? prec - bdl.scale() : 0);
3613
3614                // Add a decimal point if necessary.  The mantissa may not
3615                // contain a decimal point if the scale is zero (the internal
3616                // representation has no fractional part).  Append a decimal
3617                // point if '#' is set or we require zero padding to get to the
3618                // requested precision.
3619                if (bdl.scale() == 0 && (f.contains(Flags.ALTERNATE)
3620                        || nzeros > 0)) {
3621                    mant.append('.');
3622                }
3623
3624                // Add trailing zeros if the precision is greater than the
3625                // number of available digits after the decimal separator.
3626                trailingZeros(mant, nzeros);
3627
3628                localizedMagnitude(sb, mant, 0, f, adjustWidth(width, f, neg), l);
3629            } else if (c == Conversion.GENERAL) {
3630                int prec = precision;
3631                if (precision == -1)
3632                    prec = 6;
3633                else if (precision == 0)
3634                    prec = 1;
3635
3636                BigDecimal tenToTheNegFour = BigDecimal.valueOf(1, 4);
3637                BigDecimal tenToThePrec = BigDecimal.valueOf(1, -prec);
3638                if ((value.equals(BigDecimal.ZERO))
3639                    || ((value.compareTo(tenToTheNegFour) != -1)
3640                        && (value.compareTo(tenToThePrec) == -1))) {
3641
3642                    int e = - value.scale()
3643                        + (value.unscaledValue().toString().length() - 1);
3644
3645                    // xxx.yyy
3646                    //   g precision (# sig digits) = #x + #y
3647                    //   f precision = #y
3648                    //   exponent = #x - 1
3649                    // => f precision = g precision - exponent - 1
3650                    // 0.000zzz
3651                    //   g precision (# sig digits) = #z
3652                    //   f precision = #0 (after '.') + #z
3653                    //   exponent = - #0 (after '.') - 1
3654                    // => f precision = g precision - exponent - 1
3655                    prec = prec - e - 1;
3656
3657                    print(sb, value, l, f, Conversion.DECIMAL_FLOAT, prec,
3658                          neg);
3659                } else {
3660                    print(sb, value, l, f, Conversion.SCIENTIFIC, prec - 1, neg);
3661                }
3662            } else if (c == Conversion.HEXADECIMAL_FLOAT) {
3663                // This conversion isn't supported.  The error should be
3664                // reported earlier.
3665                assert false;
3666            }
3667        }
3668
3669        private class BigDecimalLayout {
3670            private StringBuilder mant;
3671            private StringBuilder exp;
3672            private boolean dot = false;
3673            private int scale;
3674
3675            public BigDecimalLayout(BigInteger intVal, int scale, BigDecimalLayoutForm form) {
3676                layout(intVal, scale, form);
3677            }
3678
3679            public boolean hasDot() {
3680                return dot;
3681            }
3682
3683            public int scale() {
3684                return scale;
3685            }
3686
3687            public StringBuilder mantissa() {
3688                return mant;
3689            }
3690
3691            // The exponent will be formatted as a sign ('+' or '-') followed
3692            // by the exponent zero-padded to include at least two digits.
3693            public StringBuilder exponent() {
3694                return exp;
3695            }
3696
3697            private void layout(BigInteger intVal, int scale, BigDecimalLayoutForm form) {
3698                String coeff = intVal.toString();
3699                this.scale = scale;
3700
3701                // Construct a buffer, with sufficient capacity for all cases.
3702                // If E-notation is needed, length will be: +1 if negative, +1
3703                // if '.' needed, +2 for "E+", + up to 10 for adjusted
3704                // exponent.  Otherwise it could have +1 if negative, plus
3705                // leading "0.00000"
3706                int len = coeff.length();
3707                mant = new StringBuilder(len + 14);
3708
3709                if (scale == 0) {
3710                    if (len > 1) {
3711                        mant.append(coeff.charAt(0));
3712                        if (form == BigDecimalLayoutForm.SCIENTIFIC) {
3713                            mant.append('.');
3714                            dot = true;
3715                            mant.append(coeff, 1, len);
3716                            exp = new StringBuilder("+");
3717                            if (len < 10) {
3718                                exp.append('0').append(len - 1);
3719                            } else {
3720                                exp.append(len - 1);
3721                            }
3722                        } else {
3723                            mant.append(coeff, 1, len);
3724                        }
3725                    } else {
3726                        mant.append(coeff);
3727                        if (form == BigDecimalLayoutForm.SCIENTIFIC) {
3728                            exp = new StringBuilder("+00");
3729                        }
3730                    }
3731                } else if (form == BigDecimalLayoutForm.DECIMAL_FLOAT) {
3732                    // count of padding zeros
3733
3734                    if (scale >= len) {
3735                        // 0.xxx form
3736                        mant.append("0.");
3737                        dot = true;
3738                        trailingZeros(mant, scale - len);
3739                        mant.append(coeff);
3740                    } else {
3741                        if (scale > 0) {
3742                            // xx.xx form
3743                            int pad = len - scale;
3744                            mant.append(coeff, 0, pad);
3745                            mant.append('.');
3746                            dot = true;
3747                            mant.append(coeff, pad, len);
3748                        } else { // scale < 0
3749                            // xx form
3750                            mant.append(coeff, 0, len);
3751                            if (intVal.signum() != 0) {
3752                                trailingZeros(mant, -scale);
3753                            }
3754                            this.scale = 0;
3755                        }
3756                    }
3757                } else {
3758                    // x.xxx form
3759                    mant.append(coeff.charAt(0));
3760                    if (len > 1) {
3761                        mant.append('.');
3762                        dot = true;
3763                        mant.append(coeff, 1, len);
3764                    }
3765                    exp = new StringBuilder();
3766                    long adjusted = -(long) scale + (len - 1);
3767                    if (adjusted != 0) {
3768                        long abs = Math.abs(adjusted);
3769                        // require sign
3770                        exp.append(adjusted < 0 ? '-' : '+');
3771                        if (abs < 10) {
3772                            exp.append('0');
3773                        }
3774                        exp.append(abs);
3775                    } else {
3776                        exp.append("+00");
3777                    }
3778                }
3779            }
3780        }
3781
3782        private int adjustWidth(int width, Flags f, boolean neg) {
3783            int newW = width;
3784            if (newW != -1 && neg && f.contains(Flags.PARENTHESES))
3785                newW--;
3786            return newW;
3787        }
3788
3789        // Add trailing zeros
3790        private void trailingZeros(StringBuilder sb, int nzeros) {
3791            for (int i = 0; i < nzeros; i++) {
3792                sb.append('0');
3793            }
3794        }
3795
3796        private void print(Calendar t, char c, Locale l)  throws IOException {
3797            StringBuilder sb = new StringBuilder();
3798            print(sb, t, c, l);
3799
3800            // justify based on width
3801            if (f.contains(Flags.UPPERCASE)) {
3802                appendJustified(a, sb.toString().toUpperCase());
3803            } else {
3804                appendJustified(a, sb);
3805            }
3806        }
3807
3808        private Appendable print(StringBuilder sb, Calendar t, char c, Locale l)
3809                throws IOException {
3810            if (sb == null)
3811                sb = new StringBuilder();
3812            switch (c) {
3813            case DateTime.HOUR_OF_DAY_0: // 'H' (00 - 23)
3814            case DateTime.HOUR_0:        // 'I' (01 - 12)
3815            case DateTime.HOUR_OF_DAY:   // 'k' (0 - 23) -- like H
3816            case DateTime.HOUR:        { // 'l' (1 - 12) -- like I
3817                int i = t.get(Calendar.HOUR_OF_DAY);
3818                if (c == DateTime.HOUR_0 || c == DateTime.HOUR)
3819                    i = (i == 0 || i == 12 ? 12 : i % 12);
3820                Flags flags = (c == DateTime.HOUR_OF_DAY_0
3821                               || c == DateTime.HOUR_0
3822                               ? Flags.ZERO_PAD
3823                               : Flags.NONE);
3824                sb.append(localizedMagnitude(null, i, flags, 2, l));
3825                break;
3826            }
3827            case DateTime.MINUTE:      { // 'M' (00 - 59)
3828                int i = t.get(Calendar.MINUTE);
3829                Flags flags = Flags.ZERO_PAD;
3830                sb.append(localizedMagnitude(null, i, flags, 2, l));
3831                break;
3832            }
3833            case DateTime.NANOSECOND:  { // 'N' (000000000 - 999999999)
3834                int i = t.get(Calendar.MILLISECOND) * 1000000;
3835                Flags flags = Flags.ZERO_PAD;
3836                sb.append(localizedMagnitude(null, i, flags, 9, l));
3837                break;
3838            }
3839            case DateTime.MILLISECOND: { // 'L' (000 - 999)
3840                int i = t.get(Calendar.MILLISECOND);
3841                Flags flags = Flags.ZERO_PAD;
3842                sb.append(localizedMagnitude(null, i, flags, 3, l));
3843                break;
3844            }
3845            case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?)
3846                long i = t.getTimeInMillis();
3847                Flags flags = Flags.NONE;
3848                sb.append(localizedMagnitude(null, i, flags, width, l));
3849                break;
3850            }
3851            case DateTime.AM_PM:       { // 'p' (am or pm)
3852                // Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper
3853                String[] ampm = { "AM", "PM" };
3854                if (l != null && l != Locale.US) {
3855                    DateFormatSymbols dfs = DateFormatSymbols.getInstance(l);
3856                    ampm = dfs.getAmPmStrings();
3857                }
3858                String s = ampm[t.get(Calendar.AM_PM)];
3859                sb.append(s.toLowerCase(l != null ? l : Locale.US));
3860                break;
3861            }
3862            case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?)
3863                long i = t.getTimeInMillis() / 1000;
3864                Flags flags = Flags.NONE;
3865                sb.append(localizedMagnitude(null, i, flags, width, l));
3866                break;
3867            }
3868            case DateTime.SECOND:      { // 'S' (00 - 60 - leap second)
3869                int i = t.get(Calendar.SECOND);
3870                Flags flags = Flags.ZERO_PAD;
3871                sb.append(localizedMagnitude(null, i, flags, 2, l));
3872                break;
3873            }
3874            case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus?
3875                int i = t.get(Calendar.ZONE_OFFSET) + t.get(Calendar.DST_OFFSET);
3876                boolean neg = i < 0;
3877                sb.append(neg ? '-' : '+');
3878                if (neg)
3879                    i = -i;
3880                int min = i / 60000;
3881                // combine minute and hour into a single integer
3882                int offset = (min / 60) * 100 + (min % 60);
3883                Flags flags = Flags.ZERO_PAD;
3884
3885                sb.append(localizedMagnitude(null, offset, flags, 4, l));
3886                break;
3887            }
3888            case DateTime.ZONE:        { // 'Z' (symbol)
3889                TimeZone tz = t.getTimeZone();
3890                sb.append(tz.getDisplayName((t.get(Calendar.DST_OFFSET) != 0),
3891                                           TimeZone.SHORT,
3892                                            (l == null) ? Locale.US : l));
3893                break;
3894            }
3895
3896            // Date
3897            case DateTime.NAME_OF_DAY_ABBREV:     // 'a'
3898            case DateTime.NAME_OF_DAY:          { // 'A'
3899                int i = t.get(Calendar.DAY_OF_WEEK);
3900                Locale lt = ((l == null) ? Locale.US : l);
3901                DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);
3902                if (c == DateTime.NAME_OF_DAY)
3903                    sb.append(dfs.getWeekdays()[i]);
3904                else
3905                    sb.append(dfs.getShortWeekdays()[i]);
3906                break;
3907            }
3908            case DateTime.NAME_OF_MONTH_ABBREV:   // 'b'
3909            case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b
3910            case DateTime.NAME_OF_MONTH:        { // 'B'
3911                int i = t.get(Calendar.MONTH);
3912                Locale lt = ((l == null) ? Locale.US : l);
3913                DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);
3914                if (c == DateTime.NAME_OF_MONTH)
3915                    sb.append(dfs.getMonths()[i]);
3916                else
3917                    sb.append(dfs.getShortMonths()[i]);
3918                break;
3919            }
3920            case DateTime.CENTURY:                // 'C' (00 - 99)
3921            case DateTime.YEAR_2:                 // 'y' (00 - 99)
3922            case DateTime.YEAR_4:               { // 'Y' (0000 - 9999)
3923                int i = t.get(Calendar.YEAR);
3924                int size = 2;
3925                switch (c) {
3926                case DateTime.CENTURY:
3927                    i /= 100;
3928                    break;
3929                case DateTime.YEAR_2:
3930                    i %= 100;
3931                    break;
3932                case DateTime.YEAR_4:
3933                    size = 4;
3934                    break;
3935                }
3936                Flags flags = Flags.ZERO_PAD;
3937                sb.append(localizedMagnitude(null, i, flags, size, l));
3938                break;
3939            }
3940            case DateTime.DAY_OF_MONTH_0:         // 'd' (01 - 31)
3941            case DateTime.DAY_OF_MONTH:         { // 'e' (1 - 31) -- like d
3942                int i = t.get(Calendar.DATE);
3943                Flags flags = (c == DateTime.DAY_OF_MONTH_0
3944                               ? Flags.ZERO_PAD
3945                               : Flags.NONE);
3946                sb.append(localizedMagnitude(null, i, flags, 2, l));
3947                break;
3948            }
3949            case DateTime.DAY_OF_YEAR:          { // 'j' (001 - 366)
3950                int i = t.get(Calendar.DAY_OF_YEAR);
3951                Flags flags = Flags.ZERO_PAD;
3952                sb.append(localizedMagnitude(null, i, flags, 3, l));
3953                break;
3954            }
3955            case DateTime.MONTH:                { // 'm' (01 - 12)
3956                int i = t.get(Calendar.MONTH) + 1;
3957                Flags flags = Flags.ZERO_PAD;
3958                sb.append(localizedMagnitude(null, i, flags, 2, l));
3959                break;
3960            }
3961
3962            // Composites
3963            case DateTime.TIME:         // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS)
3964            case DateTime.TIME_24_HOUR:    { // 'R' (hh:mm same as %H:%M)
3965                char sep = ':';
3966                print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep);
3967                print(sb, t, DateTime.MINUTE, l);
3968                if (c == DateTime.TIME) {
3969                    sb.append(sep);
3970                    print(sb, t, DateTime.SECOND, l);
3971                }
3972                break;
3973            }
3974            case DateTime.TIME_12_HOUR:    { // 'r' (hh:mm:ss [AP]M)
3975                char sep = ':';
3976                print(sb, t, DateTime.HOUR_0, l).append(sep);
3977                print(sb, t, DateTime.MINUTE, l).append(sep);
3978                print(sb, t, DateTime.SECOND, l).append(' ');
3979                // this may be in wrong place for some locales
3980                StringBuilder tsb = new StringBuilder();
3981                print(tsb, t, DateTime.AM_PM, l);
3982
3983                sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US));
3984                break;
3985            }
3986            case DateTime.DATE_TIME:    { // 'c' (Sat Nov 04 12:02:33 EST 1999)
3987                char sep = ' ';
3988                print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep);
3989                print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep);
3990                print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);
3991                print(sb, t, DateTime.TIME, l).append(sep);
3992                print(sb, t, DateTime.ZONE, l).append(sep);
3993                print(sb, t, DateTime.YEAR_4, l);
3994                break;
3995            }
3996            case DateTime.DATE:            { // 'D' (mm/dd/yy)
3997                char sep = '/';
3998                print(sb, t, DateTime.MONTH, l).append(sep);
3999                print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);
4000                print(sb, t, DateTime.YEAR_2, l);
4001                break;
4002            }
4003            case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d)
4004                char sep = '-';
4005                print(sb, t, DateTime.YEAR_4, l).append(sep);
4006                print(sb, t, DateTime.MONTH, l).append(sep);
4007                print(sb, t, DateTime.DAY_OF_MONTH_0, l);
4008                break;
4009            }
4010            default:
4011                assert false;
4012            }
4013            return sb;
4014        }
4015
4016        private void print(TemporalAccessor t, char c, Locale l)  throws IOException {
4017            StringBuilder sb = new StringBuilder();
4018            print(sb, t, c, l);
4019            // justify based on width
4020            if (f.contains(Flags.UPPERCASE)) {
4021                appendJustified(a, sb.toString().toUpperCase());
4022            } else {
4023                appendJustified(a, sb);
4024            }
4025        }
4026
4027        private Appendable print(StringBuilder sb, TemporalAccessor t, char c,
4028                                 Locale l) throws IOException {
4029            if (sb == null)
4030                sb = new StringBuilder();
4031            try {
4032                switch (c) {
4033                case DateTime.HOUR_OF_DAY_0: {  // 'H' (00 - 23)
4034                    int i = t.get(ChronoField.HOUR_OF_DAY);
4035                    sb.append(localizedMagnitude(null, i, Flags.ZERO_PAD, 2, l));
4036                    break;
4037                }
4038                case DateTime.HOUR_OF_DAY: {   // 'k' (0 - 23) -- like H
4039                    int i = t.get(ChronoField.HOUR_OF_DAY);
4040                    sb.append(localizedMagnitude(null, i, Flags.NONE, 2, l));
4041                    break;
4042                }
4043                case DateTime.HOUR_0:      {  // 'I' (01 - 12)
4044                    int i = t.get(ChronoField.CLOCK_HOUR_OF_AMPM);
4045                    sb.append(localizedMagnitude(null, i, Flags.ZERO_PAD, 2, l));
4046                    break;
4047                }
4048                case DateTime.HOUR:        { // 'l' (1 - 12) -- like I
4049                    int i = t.get(ChronoField.CLOCK_HOUR_OF_AMPM);
4050                    sb.append(localizedMagnitude(null, i, Flags.NONE, 2, l));
4051                    break;
4052                }
4053                case DateTime.MINUTE:      { // 'M' (00 - 59)
4054                    int i = t.get(ChronoField.MINUTE_OF_HOUR);
4055                    Flags flags = Flags.ZERO_PAD;
4056                    sb.append(localizedMagnitude(null, i, flags, 2, l));
4057                    break;
4058                }
4059                case DateTime.NANOSECOND:  { // 'N' (000000000 - 999999999)
4060                    int i;
4061                    try {
4062                        i = t.get(ChronoField.NANO_OF_SECOND);
4063                    } catch (UnsupportedTemporalTypeException u) {
4064                        i = t.get(ChronoField.MILLI_OF_SECOND) * 1000000;
4065                    }
4066                    Flags flags = Flags.ZERO_PAD;
4067                    sb.append(localizedMagnitude(null, i, flags, 9, l));
4068                    break;
4069                }
4070                case DateTime.MILLISECOND: { // 'L' (000 - 999)
4071                    int i = t.get(ChronoField.MILLI_OF_SECOND);
4072                    Flags flags = Flags.ZERO_PAD;
4073                    sb.append(localizedMagnitude(null, i, flags, 3, l));
4074                    break;
4075                }
4076                case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?)
4077                    long i = t.getLong(ChronoField.INSTANT_SECONDS) * 1000L +
4078                             t.getLong(ChronoField.MILLI_OF_SECOND);
4079                    Flags flags = Flags.NONE;
4080                    sb.append(localizedMagnitude(null, i, flags, width, l));
4081                    break;
4082                }
4083                case DateTime.AM_PM:       { // 'p' (am or pm)
4084                    // Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper
4085                    String[] ampm = { "AM", "PM" };
4086                    if (l != null && l != Locale.US) {
4087                        DateFormatSymbols dfs = DateFormatSymbols.getInstance(l);
4088                        ampm = dfs.getAmPmStrings();
4089                    }
4090                    String s = ampm[t.get(ChronoField.AMPM_OF_DAY)];
4091                    sb.append(s.toLowerCase(l != null ? l : Locale.US));
4092                    break;
4093                }
4094                case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?)
4095                    long i = t.getLong(ChronoField.INSTANT_SECONDS);
4096                    Flags flags = Flags.NONE;
4097                    sb.append(localizedMagnitude(null, i, flags, width, l));
4098                    break;
4099                }
4100                case DateTime.SECOND:      { // 'S' (00 - 60 - leap second)
4101                    int i = t.get(ChronoField.SECOND_OF_MINUTE);
4102                    Flags flags = Flags.ZERO_PAD;
4103                    sb.append(localizedMagnitude(null, i, flags, 2, l));
4104                    break;
4105                }
4106                case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus?
4107                    int i = t.get(ChronoField.OFFSET_SECONDS);
4108                    boolean neg = i < 0;
4109                    sb.append(neg ? '-' : '+');
4110                    if (neg)
4111                        i = -i;
4112                    int min = i / 60;
4113                    // combine minute and hour into a single integer
4114                    int offset = (min / 60) * 100 + (min % 60);
4115                    Flags flags = Flags.ZERO_PAD;
4116                    sb.append(localizedMagnitude(null, offset, flags, 4, l));
4117                    break;
4118                }
4119                case DateTime.ZONE:        { // 'Z' (symbol)
4120                    ZoneId zid = t.query(TemporalQueries.zone());
4121                    if (zid == null) {
4122                        throw new IllegalFormatConversionException(c, t.getClass());
4123                    }
4124                    if (!(zid instanceof ZoneOffset) &&
4125                        t.isSupported(ChronoField.INSTANT_SECONDS)) {
4126                        Instant instant = Instant.from(t);
4127                        sb.append(TimeZone.getTimeZone(zid.getId())
4128                                          .getDisplayName(zid.getRules().isDaylightSavings(instant),
4129                                                          TimeZone.SHORT,
4130                                                          (l == null) ? Locale.US : l));
4131                        break;
4132                    }
4133                    sb.append(zid.getId());
4134                    break;
4135                }
4136                // Date
4137                case DateTime.NAME_OF_DAY_ABBREV:     // 'a'
4138                case DateTime.NAME_OF_DAY:          { // 'A'
4139                    int i = t.get(ChronoField.DAY_OF_WEEK) % 7 + 1;
4140                    Locale lt = ((l == null) ? Locale.US : l);
4141                    DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);
4142                    if (c == DateTime.NAME_OF_DAY)
4143                        sb.append(dfs.getWeekdays()[i]);
4144                    else
4145                        sb.append(dfs.getShortWeekdays()[i]);
4146                    break;
4147                }
4148                case DateTime.NAME_OF_MONTH_ABBREV:   // 'b'
4149                case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b
4150                case DateTime.NAME_OF_MONTH:        { // 'B'
4151                    int i = t.get(ChronoField.MONTH_OF_YEAR) - 1;
4152                    Locale lt = ((l == null) ? Locale.US : l);
4153                    DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);
4154                    if (c == DateTime.NAME_OF_MONTH)
4155                        sb.append(dfs.getMonths()[i]);
4156                    else
4157                        sb.append(dfs.getShortMonths()[i]);
4158                    break;
4159                }
4160                case DateTime.CENTURY:                // 'C' (00 - 99)
4161                case DateTime.YEAR_2:                 // 'y' (00 - 99)
4162                case DateTime.YEAR_4:               { // 'Y' (0000 - 9999)
4163                    int i = t.get(ChronoField.YEAR_OF_ERA);
4164                    int size = 2;
4165                    switch (c) {
4166                    case DateTime.CENTURY:
4167                        i /= 100;
4168                        break;
4169                    case DateTime.YEAR_2:
4170                        i %= 100;
4171                        break;
4172                    case DateTime.YEAR_4:
4173                        size = 4;
4174                        break;
4175                    }
4176                    Flags flags = Flags.ZERO_PAD;
4177                    sb.append(localizedMagnitude(null, i, flags, size, l));
4178                    break;
4179                }
4180                case DateTime.DAY_OF_MONTH_0:         // 'd' (01 - 31)
4181                case DateTime.DAY_OF_MONTH:         { // 'e' (1 - 31) -- like d
4182                    int i = t.get(ChronoField.DAY_OF_MONTH);
4183                    Flags flags = (c == DateTime.DAY_OF_MONTH_0
4184                                   ? Flags.ZERO_PAD
4185                                   : Flags.NONE);
4186                    sb.append(localizedMagnitude(null, i, flags, 2, l));
4187                    break;
4188                }
4189                case DateTime.DAY_OF_YEAR:          { // 'j' (001 - 366)
4190                    int i = t.get(ChronoField.DAY_OF_YEAR);
4191                    Flags flags = Flags.ZERO_PAD;
4192                    sb.append(localizedMagnitude(null, i, flags, 3, l));
4193                    break;
4194                }
4195                case DateTime.MONTH:                { // 'm' (01 - 12)
4196                    int i = t.get(ChronoField.MONTH_OF_YEAR);
4197                    Flags flags = Flags.ZERO_PAD;
4198                    sb.append(localizedMagnitude(null, i, flags, 2, l));
4199                    break;
4200                }
4201
4202                // Composites
4203                case DateTime.TIME:         // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS)
4204                case DateTime.TIME_24_HOUR:    { // 'R' (hh:mm same as %H:%M)
4205                    char sep = ':';
4206                    print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep);
4207                    print(sb, t, DateTime.MINUTE, l);
4208                    if (c == DateTime.TIME) {
4209                        sb.append(sep);
4210                        print(sb, t, DateTime.SECOND, l);
4211                    }
4212                    break;
4213                }
4214                case DateTime.TIME_12_HOUR:    { // 'r' (hh:mm:ss [AP]M)
4215                    char sep = ':';
4216                    print(sb, t, DateTime.HOUR_0, l).append(sep);
4217                    print(sb, t, DateTime.MINUTE, l).append(sep);
4218                    print(sb, t, DateTime.SECOND, l).append(' ');
4219                    // this may be in wrong place for some locales
4220                    StringBuilder tsb = new StringBuilder();
4221                    print(tsb, t, DateTime.AM_PM, l);
4222                    sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US));
4223                    break;
4224                }
4225                case DateTime.DATE_TIME:    { // 'c' (Sat Nov 04 12:02:33 EST 1999)
4226                    char sep = ' ';
4227                    print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep);
4228                    print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep);
4229                    print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);
4230                    print(sb, t, DateTime.TIME, l).append(sep);
4231                    print(sb, t, DateTime.ZONE, l).append(sep);
4232                    print(sb, t, DateTime.YEAR_4, l);
4233                    break;
4234                }
4235                case DateTime.DATE:            { // 'D' (mm/dd/yy)
4236                    char sep = '/';
4237                    print(sb, t, DateTime.MONTH, l).append(sep);
4238                    print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);
4239                    print(sb, t, DateTime.YEAR_2, l);
4240                    break;
4241                }
4242                case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d)
4243                    char sep = '-';
4244                    print(sb, t, DateTime.YEAR_4, l).append(sep);
4245                    print(sb, t, DateTime.MONTH, l).append(sep);
4246                    print(sb, t, DateTime.DAY_OF_MONTH_0, l);
4247                    break;
4248                }
4249                default:
4250                    assert false;
4251                }
4252            } catch (DateTimeException x) {
4253                throw new IllegalFormatConversionException(c, t.getClass());
4254            }
4255            return sb;
4256        }
4257
4258        // -- Methods to support throwing exceptions --
4259
4260        private void failMismatch(Flags f, char c) {
4261            String fs = f.toString();
4262            throw new FormatFlagsConversionMismatchException(fs, c);
4263        }
4264
4265        private void failConversion(char c, Object arg) {
4266            throw new IllegalFormatConversionException(c, arg.getClass());
4267        }
4268
4269        private char getZero(Locale l) {
4270            if ((l != null) &&  !l.equals(locale())) {
4271                DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
4272                return dfs.getZeroDigit();
4273            }
4274            return zero;
4275        }
4276
4277        private StringBuilder localizedMagnitude(StringBuilder sb,
4278                long value, Flags f, int width, Locale l) {
4279            return localizedMagnitude(sb, Long.toString(value, 10), 0, f, width, l);
4280        }
4281
4282        private StringBuilder localizedMagnitude(StringBuilder sb,
4283                CharSequence value, final int offset, Flags f, int width,
4284                Locale l) {
4285            if (sb == null) {
4286                sb = new StringBuilder();
4287            }
4288            int begin = sb.length();
4289
4290            char zero = getZero(l);
4291
4292            // determine localized grouping separator and size
4293            char grpSep = '\0';
4294            int  grpSize = -1;
4295            char decSep = '\0';
4296
4297            int len = value.length();
4298            int dot = len;
4299            for (int j = offset; j < len; j++) {
4300                if (value.charAt(j) == '.') {
4301                    dot = j;
4302                    break;
4303                }
4304            }
4305
4306            if (dot < len) {
4307                if (l == null || l.equals(Locale.US)) {
4308                    decSep  = '.';
4309                } else {
4310                    DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
4311                    decSep  = dfs.getDecimalSeparator();
4312                }
4313            }
4314
4315            if (f.contains(Flags.GROUP)) {
4316                if (l == null || l.equals(Locale.US)) {
4317                    grpSep = ',';
4318                    grpSize = 3;
4319                } else {
4320                    DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
4321                    grpSep = dfs.getGroupingSeparator();
4322                    DecimalFormat df = (DecimalFormat) NumberFormat.getIntegerInstance(l);
4323                    grpSize = df.getGroupingSize();
4324                }
4325            }
4326
4327            // localize the digits inserting group separators as necessary
4328            for (int j = offset; j < len; j++) {
4329                if (j == dot) {
4330                    sb.append(decSep);
4331                    // no more group separators after the decimal separator
4332                    grpSep = '\0';
4333                    continue;
4334                }
4335
4336                char c = value.charAt(j);
4337                sb.append((char) ((c - '0') + zero));
4338                if (grpSep != '\0' && j != dot - 1 && ((dot - j) % grpSize == 1)) {
4339                    sb.append(grpSep);
4340                }
4341            }
4342
4343            // apply zero padding
4344            if (width != -1 && f.contains(Flags.ZERO_PAD)) {
4345                for (int k = sb.length(); k < width; k++) {
4346                    sb.insert(begin, zero);
4347                }
4348            }
4349
4350            return sb;
4351        }
4352
4353        // Specialized localization of exponents, where the source value can only
4354        // contain characters '0' through '9', starting at index offset, and no
4355        // group separators is added for any locale.
4356        private void localizedMagnitudeExp(StringBuilder sb, char[] value,
4357                final int offset, Locale l) {
4358            char zero = getZero(l);
4359
4360            int len = value.length;
4361            for (int j = offset; j < len; j++) {
4362                char c = value[j];
4363                sb.append((char) ((c - '0') + zero));
4364            }
4365        }
4366    }
4367
4368    private static class Flags {
4369        private int flags;
4370
4371        static final Flags NONE          = new Flags(0);      // ''
4372
4373        // duplicate declarations from Formattable.java
4374        static final Flags LEFT_JUSTIFY  = new Flags(1<<0);   // '-'
4375        static final Flags UPPERCASE     = new Flags(1<<1);   // '^'
4376        static final Flags ALTERNATE     = new Flags(1<<2);   // '#'
4377
4378        // numerics
4379        static final Flags PLUS          = new Flags(1<<3);   // '+'
4380        static final Flags LEADING_SPACE = new Flags(1<<4);   // ' '
4381        static final Flags ZERO_PAD      = new Flags(1<<5);   // '0'
4382        static final Flags GROUP         = new Flags(1<<6);   // ','
4383        static final Flags PARENTHESES   = new Flags(1<<7);   // '('
4384
4385        // indexing
4386        static final Flags PREVIOUS      = new Flags(1<<8);   // '<'
4387
4388        private Flags(int f) {
4389            flags = f;
4390        }
4391
4392        public int valueOf() {
4393            return flags;
4394        }
4395
4396        public boolean contains(Flags f) {
4397            return (flags & f.valueOf()) == f.valueOf();
4398        }
4399
4400        public Flags dup() {
4401            return new Flags(flags);
4402        }
4403
4404        private Flags add(Flags f) {
4405            flags |= f.valueOf();
4406            return this;
4407        }
4408
4409        public Flags remove(Flags f) {
4410            flags &= ~f.valueOf();
4411            return this;
4412        }
4413
4414        public static Flags parse(String s, int start, int end) {
4415            Flags f = new Flags(0);
4416            for (int i = start; i < end; i++) {
4417                char c = s.charAt(i);
4418                Flags v = parse(c);
4419                if (f.contains(v))
4420                    throw new DuplicateFormatFlagsException(v.toString());
4421                f.add(v);
4422            }
4423            return f;
4424        }
4425
4426        // parse those flags which may be provided by users
4427        private static Flags parse(char c) {
4428            switch (c) {
4429            case '-': return LEFT_JUSTIFY;
4430            case '#': return ALTERNATE;
4431            case '+': return PLUS;
4432            case ' ': return LEADING_SPACE;
4433            case '0': return ZERO_PAD;
4434            case ',': return GROUP;
4435            case '(': return PARENTHESES;
4436            case '<': return PREVIOUS;
4437            default:
4438                throw new UnknownFormatFlagsException(String.valueOf(c));
4439            }
4440        }
4441
4442        // Returns a string representation of the current {@code Flags}.
4443        public static String toString(Flags f) {
4444            return f.toString();
4445        }
4446
4447        public String toString() {
4448            StringBuilder sb = new StringBuilder();
4449            if (contains(LEFT_JUSTIFY))  sb.append('-');
4450            if (contains(UPPERCASE))     sb.append('^');
4451            if (contains(ALTERNATE))     sb.append('#');
4452            if (contains(PLUS))          sb.append('+');
4453            if (contains(LEADING_SPACE)) sb.append(' ');
4454            if (contains(ZERO_PAD))      sb.append('0');
4455            if (contains(GROUP))         sb.append(',');
4456            if (contains(PARENTHESES))   sb.append('(');
4457            if (contains(PREVIOUS))      sb.append('<');
4458            return sb.toString();
4459        }
4460    }
4461
4462    private static class Conversion {
4463        // Byte, Short, Integer, Long, BigInteger
4464        // (and associated primitives due to autoboxing)
4465        static final char DECIMAL_INTEGER     = 'd';
4466        static final char OCTAL_INTEGER       = 'o';
4467        static final char HEXADECIMAL_INTEGER = 'x';
4468        static final char HEXADECIMAL_INTEGER_UPPER = 'X';
4469
4470        // Float, Double, BigDecimal
4471        // (and associated primitives due to autoboxing)
4472        static final char SCIENTIFIC          = 'e';
4473        static final char SCIENTIFIC_UPPER    = 'E';
4474        static final char GENERAL             = 'g';
4475        static final char GENERAL_UPPER       = 'G';
4476        static final char DECIMAL_FLOAT       = 'f';
4477        static final char HEXADECIMAL_FLOAT   = 'a';
4478        static final char HEXADECIMAL_FLOAT_UPPER = 'A';
4479
4480        // Character, Byte, Short, Integer
4481        // (and associated primitives due to autoboxing)
4482        static final char CHARACTER           = 'c';
4483        static final char CHARACTER_UPPER     = 'C';
4484
4485        // java.util.Date, java.util.Calendar, long
4486        static final char DATE_TIME           = 't';
4487        static final char DATE_TIME_UPPER     = 'T';
4488
4489        // if (arg.TYPE != boolean) return boolean
4490        // if (arg != null) return true; else return false;
4491        static final char BOOLEAN             = 'b';
4492        static final char BOOLEAN_UPPER       = 'B';
4493        // if (arg instanceof Formattable) arg.formatTo()
4494        // else arg.toString();
4495        static final char STRING              = 's';
4496        static final char STRING_UPPER        = 'S';
4497        // arg.hashCode()
4498        static final char HASHCODE            = 'h';
4499        static final char HASHCODE_UPPER      = 'H';
4500
4501        static final char LINE_SEPARATOR      = 'n';
4502        static final char PERCENT_SIGN        = '%';
4503
4504        static boolean isValid(char c) {
4505            return (isGeneral(c) || isInteger(c) || isFloat(c) || isText(c)
4506                    || c == 't' || isCharacter(c));
4507        }
4508
4509        // Returns true iff the Conversion is applicable to all objects.
4510        static boolean isGeneral(char c) {
4511            switch (c) {
4512            case BOOLEAN:
4513            case BOOLEAN_UPPER:
4514            case STRING:
4515            case STRING_UPPER:
4516            case HASHCODE:
4517            case HASHCODE_UPPER:
4518                return true;
4519            default:
4520                return false;
4521            }
4522        }
4523
4524        // Returns true iff the Conversion is applicable to character.
4525        static boolean isCharacter(char c) {
4526            switch (c) {
4527            case CHARACTER:
4528            case CHARACTER_UPPER:
4529                return true;
4530            default:
4531                return false;
4532            }
4533        }
4534
4535        // Returns true iff the Conversion is an integer type.
4536        static boolean isInteger(char c) {
4537            switch (c) {
4538            case DECIMAL_INTEGER:
4539            case OCTAL_INTEGER:
4540            case HEXADECIMAL_INTEGER:
4541            case HEXADECIMAL_INTEGER_UPPER:
4542                return true;
4543            default:
4544                return false;
4545            }
4546        }
4547
4548        // Returns true iff the Conversion is a floating-point type.
4549        static boolean isFloat(char c) {
4550            switch (c) {
4551            case SCIENTIFIC:
4552            case SCIENTIFIC_UPPER:
4553            case GENERAL:
4554            case GENERAL_UPPER:
4555            case DECIMAL_FLOAT:
4556            case HEXADECIMAL_FLOAT:
4557            case HEXADECIMAL_FLOAT_UPPER:
4558                return true;
4559            default:
4560                return false;
4561            }
4562        }
4563
4564        // Returns true iff the Conversion does not require an argument
4565        static boolean isText(char c) {
4566            switch (c) {
4567            case LINE_SEPARATOR:
4568            case PERCENT_SIGN:
4569                return true;
4570            default:
4571                return false;
4572            }
4573        }
4574    }
4575
4576    private static class DateTime {
4577        static final char HOUR_OF_DAY_0 = 'H'; // (00 - 23)
4578        static final char HOUR_0        = 'I'; // (01 - 12)
4579        static final char HOUR_OF_DAY   = 'k'; // (0 - 23) -- like H
4580        static final char HOUR          = 'l'; // (1 - 12) -- like I
4581        static final char MINUTE        = 'M'; // (00 - 59)
4582        static final char NANOSECOND    = 'N'; // (000000000 - 999999999)
4583        static final char MILLISECOND   = 'L'; // jdk, not in gnu (000 - 999)
4584        static final char MILLISECOND_SINCE_EPOCH = 'Q'; // (0 - 99...?)
4585        static final char AM_PM         = 'p'; // (am or pm)
4586        static final char SECONDS_SINCE_EPOCH = 's'; // (0 - 99...?)
4587        static final char SECOND        = 'S'; // (00 - 60 - leap second)
4588        static final char TIME          = 'T'; // (24 hour hh:mm:ss)
4589        static final char ZONE_NUMERIC  = 'z'; // (-1200 - +1200) - ls minus?
4590        static final char ZONE          = 'Z'; // (symbol)
4591
4592        // Date
4593        static final char NAME_OF_DAY_ABBREV    = 'a'; // 'a'
4594        static final char NAME_OF_DAY           = 'A'; // 'A'
4595        static final char NAME_OF_MONTH_ABBREV  = 'b'; // 'b'
4596        static final char NAME_OF_MONTH         = 'B'; // 'B'
4597        static final char CENTURY               = 'C'; // (00 - 99)
4598        static final char DAY_OF_MONTH_0        = 'd'; // (01 - 31)
4599        static final char DAY_OF_MONTH          = 'e'; // (1 - 31) -- like d
4600// *    static final char ISO_WEEK_OF_YEAR_2    = 'g'; // cross %y %V
4601// *    static final char ISO_WEEK_OF_YEAR_4    = 'G'; // cross %Y %V
4602        static final char NAME_OF_MONTH_ABBREV_X  = 'h'; // -- same b
4603        static final char DAY_OF_YEAR           = 'j'; // (001 - 366)
4604        static final char MONTH                 = 'm'; // (01 - 12)
4605// *    static final char DAY_OF_WEEK_1         = 'u'; // (1 - 7) Monday
4606// *    static final char WEEK_OF_YEAR_SUNDAY   = 'U'; // (0 - 53) Sunday+
4607// *    static final char WEEK_OF_YEAR_MONDAY_01 = 'V'; // (01 - 53) Monday+
4608// *    static final char DAY_OF_WEEK_0         = 'w'; // (0 - 6) Sunday
4609// *    static final char WEEK_OF_YEAR_MONDAY   = 'W'; // (00 - 53) Monday
4610        static final char YEAR_2                = 'y'; // (00 - 99)
4611        static final char YEAR_4                = 'Y'; // (0000 - 9999)
4612
4613        // Composites
4614        static final char TIME_12_HOUR  = 'r'; // (hh:mm:ss [AP]M)
4615        static final char TIME_24_HOUR  = 'R'; // (hh:mm same as %H:%M)
4616// *    static final char LOCALE_TIME   = 'X'; // (%H:%M:%S) - parse format?
4617        static final char DATE_TIME             = 'c';
4618                                            // (Sat Nov 04 12:02:33 EST 1999)
4619        static final char DATE                  = 'D'; // (mm/dd/yy)
4620        static final char ISO_STANDARD_DATE     = 'F'; // (%Y-%m-%d)
4621// *    static final char LOCALE_DATE           = 'x'; // (mm/dd/yy)
4622
4623        static boolean isValid(char c) {
4624            switch (c) {
4625            case HOUR_OF_DAY_0:
4626            case HOUR_0:
4627            case HOUR_OF_DAY:
4628            case HOUR:
4629            case MINUTE:
4630            case NANOSECOND:
4631            case MILLISECOND:
4632            case MILLISECOND_SINCE_EPOCH:
4633            case AM_PM:
4634            case SECONDS_SINCE_EPOCH:
4635            case SECOND:
4636            case TIME:
4637            case ZONE_NUMERIC:
4638            case ZONE:
4639
4640            // Date
4641            case NAME_OF_DAY_ABBREV:
4642            case NAME_OF_DAY:
4643            case NAME_OF_MONTH_ABBREV:
4644            case NAME_OF_MONTH:
4645            case CENTURY:
4646            case DAY_OF_MONTH_0:
4647            case DAY_OF_MONTH:
4648// *        case ISO_WEEK_OF_YEAR_2:
4649// *        case ISO_WEEK_OF_YEAR_4:
4650            case NAME_OF_MONTH_ABBREV_X:
4651            case DAY_OF_YEAR:
4652            case MONTH:
4653// *        case DAY_OF_WEEK_1:
4654// *        case WEEK_OF_YEAR_SUNDAY:
4655// *        case WEEK_OF_YEAR_MONDAY_01:
4656// *        case DAY_OF_WEEK_0:
4657// *        case WEEK_OF_YEAR_MONDAY:
4658            case YEAR_2:
4659            case YEAR_4:
4660
4661            // Composites
4662            case TIME_12_HOUR:
4663            case TIME_24_HOUR:
4664// *        case LOCALE_TIME:
4665            case DATE_TIME:
4666            case DATE:
4667            case ISO_STANDARD_DATE:
4668// *        case LOCALE_DATE:
4669                return true;
4670            default:
4671                return false;
4672            }
4673        }
4674    }
4675}
4676