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