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