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