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