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