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