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