rt/emul/mini/src/main/java/java/lang/Integer.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 07 Jul 2015 07:46:52 +0200
changeset 1837 62b289bb87c7
parent 772 d382dacfd73f
permissions -rw-r--r--
Throwing more of NumberFormatException when parsing numbers
     1 /*
     2  * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package java.lang;
    27 
    28 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    29 
    30 /**
    31  * The {@code Integer} class wraps a value of the primitive type
    32  * {@code int} in an object. An object of type {@code Integer}
    33  * contains a single field whose type is {@code int}.
    34  *
    35  * <p>In addition, this class provides several methods for converting
    36  * an {@code int} to a {@code String} and a {@code String} to an
    37  * {@code int}, as well as other constants and methods useful when
    38  * dealing with an {@code int}.
    39  *
    40  * <p>Implementation note: The implementations of the "bit twiddling"
    41  * methods (such as {@link #highestOneBit(int) highestOneBit} and
    42  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
    43  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
    44  * Delight</i>, (Addison Wesley, 2002).
    45  *
    46  * @author  Lee Boynton
    47  * @author  Arthur van Hoff
    48  * @author  Josh Bloch
    49  * @author  Joseph D. Darcy
    50  * @since JDK1.0
    51  */
    52 public final class Integer extends Number implements Comparable<Integer> {
    53     /**
    54      * A constant holding the minimum value an {@code int} can
    55      * have, -2<sup>31</sup>.
    56      */
    57     public static final int   MIN_VALUE = 0x80000000;
    58 
    59     /**
    60      * A constant holding the maximum value an {@code int} can
    61      * have, 2<sup>31</sup>-1.
    62      */
    63     public static final int   MAX_VALUE = 0x7fffffff;
    64 
    65     /**
    66      * The {@code Class} instance representing the primitive type
    67      * {@code int}.
    68      *
    69      * @since   JDK1.1
    70      */
    71     public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
    72 
    73     /**
    74      * All possible chars for representing a number as a String
    75      */
    76     final static char[] digits = {
    77         '0' , '1' , '2' , '3' , '4' , '5' ,
    78         '6' , '7' , '8' , '9' , 'a' , 'b' ,
    79         'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
    80         'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
    81         'o' , 'p' , 'q' , 'r' , 's' , 't' ,
    82         'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    83     };
    84 
    85     /**
    86      * Returns a string representation of the first argument in the
    87      * radix specified by the second argument.
    88      *
    89      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
    90      * or larger than {@code Character.MAX_RADIX}, then the radix
    91      * {@code 10} is used instead.
    92      *
    93      * <p>If the first argument is negative, the first element of the
    94      * result is the ASCII minus character {@code '-'}
    95      * (<code>'&#92;u002D'</code>). If the first argument is not
    96      * negative, no sign character appears in the result.
    97      *
    98      * <p>The remaining characters of the result represent the magnitude
    99      * of the first argument. If the magnitude is zero, it is
   100      * represented by a single zero character {@code '0'}
   101      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   102      * the representation of the magnitude will not be the zero
   103      * character.  The following ASCII characters are used as digits:
   104      *
   105      * <blockquote>
   106      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
   107      * </blockquote>
   108      *
   109      * These are <code>'&#92;u0030'</code> through
   110      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
   111      * <code>'&#92;u007A'</code>. If {@code radix} is
   112      * <var>N</var>, then the first <var>N</var> of these characters
   113      * are used as radix-<var>N</var> digits in the order shown. Thus,
   114      * the digits for hexadecimal (radix 16) are
   115      * {@code 0123456789abcdef}. If uppercase letters are
   116      * desired, the {@link java.lang.String#toUpperCase()} method may
   117      * be called on the result:
   118      *
   119      * <blockquote>
   120      *  {@code Integer.toString(n, 16).toUpperCase()}
   121      * </blockquote>
   122      *
   123      * @param   i       an integer to be converted to a string.
   124      * @param   radix   the radix to use in the string representation.
   125      * @return  a string representation of the argument in the specified radix.
   126      * @see     java.lang.Character#MAX_RADIX
   127      * @see     java.lang.Character#MIN_RADIX
   128      */
   129     public static String toString(int i, int radix) {
   130 
   131         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
   132             radix = 10;
   133 
   134         /* Use the faster version */
   135         if (radix == 10) {
   136             return toString(i);
   137         }
   138 
   139         char buf[] = new char[33];
   140         boolean negative = (i < 0);
   141         int charPos = 32;
   142 
   143         if (!negative) {
   144             i = -i;
   145         }
   146 
   147         while (i <= -radix) {
   148             buf[charPos--] = digits[-(i % radix)];
   149             i = i / radix;
   150         }
   151         buf[charPos] = digits[-i];
   152 
   153         if (negative) {
   154             buf[--charPos] = '-';
   155         }
   156 
   157         return new String(buf, charPos, (33 - charPos));
   158     }
   159 
   160     /**
   161      * Returns a string representation of the integer argument as an
   162      * unsigned integer in base&nbsp;16.
   163      *
   164      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
   165      * if the argument is negative; otherwise, it is equal to the
   166      * argument.  This value is converted to a string of ASCII digits
   167      * in hexadecimal (base&nbsp;16) with no extra leading
   168      * {@code 0}s. If the unsigned magnitude is zero, it is
   169      * represented by a single zero character {@code '0'}
   170      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   171      * the representation of the unsigned magnitude will not be the
   172      * zero character. The following characters are used as
   173      * hexadecimal digits:
   174      *
   175      * <blockquote>
   176      *  {@code 0123456789abcdef}
   177      * </blockquote>
   178      *
   179      * These are the characters <code>'&#92;u0030'</code> through
   180      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
   181      * <code>'&#92;u0066'</code>. If uppercase letters are
   182      * desired, the {@link java.lang.String#toUpperCase()} method may
   183      * be called on the result:
   184      *
   185      * <blockquote>
   186      *  {@code Integer.toHexString(n).toUpperCase()}
   187      * </blockquote>
   188      *
   189      * @param   i   an integer to be converted to a string.
   190      * @return  the string representation of the unsigned integer value
   191      *          represented by the argument in hexadecimal (base&nbsp;16).
   192      * @since   JDK1.0.2
   193      */
   194     public static String toHexString(int i) {
   195         return toUnsignedString(i, 4);
   196     }
   197 
   198     /**
   199      * Returns a string representation of the integer argument as an
   200      * unsigned integer in base&nbsp;8.
   201      *
   202      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
   203      * if the argument is negative; otherwise, it is equal to the
   204      * argument.  This value is converted to a string of ASCII digits
   205      * in octal (base&nbsp;8) with no extra leading {@code 0}s.
   206      *
   207      * <p>If the unsigned magnitude is zero, it is represented by a
   208      * single zero character {@code '0'}
   209      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   210      * the representation of the unsigned magnitude will not be the
   211      * zero character. The following characters are used as octal
   212      * digits:
   213      *
   214      * <blockquote>
   215      * {@code 01234567}
   216      * </blockquote>
   217      *
   218      * These are the characters <code>'&#92;u0030'</code> through
   219      * <code>'&#92;u0037'</code>.
   220      *
   221      * @param   i   an integer to be converted to a string.
   222      * @return  the string representation of the unsigned integer value
   223      *          represented by the argument in octal (base&nbsp;8).
   224      * @since   JDK1.0.2
   225      */
   226     public static String toOctalString(int i) {
   227         return toUnsignedString(i, 3);
   228     }
   229 
   230     /**
   231      * Returns a string representation of the integer argument as an
   232      * unsigned integer in base&nbsp;2.
   233      *
   234      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
   235      * if the argument is negative; otherwise it is equal to the
   236      * argument.  This value is converted to a string of ASCII digits
   237      * in binary (base&nbsp;2) with no extra leading {@code 0}s.
   238      * If the unsigned magnitude is zero, it is represented by a
   239      * single zero character {@code '0'}
   240      * (<code>'&#92;u0030'</code>); otherwise, the first character of
   241      * the representation of the unsigned magnitude will not be the
   242      * zero character. The characters {@code '0'}
   243      * (<code>'&#92;u0030'</code>) and {@code '1'}
   244      * (<code>'&#92;u0031'</code>) are used as binary digits.
   245      *
   246      * @param   i   an integer to be converted to a string.
   247      * @return  the string representation of the unsigned integer value
   248      *          represented by the argument in binary (base&nbsp;2).
   249      * @since   JDK1.0.2
   250      */
   251     public static String toBinaryString(int i) {
   252         return toUnsignedString(i, 1);
   253     }
   254 
   255     /**
   256      * Convert the integer to an unsigned number.
   257      */
   258     private static String toUnsignedString(int i, int shift) {
   259         char[] buf = new char[32];
   260         int charPos = 32;
   261         int radix = 1 << shift;
   262         int mask = radix - 1;
   263         do {
   264             buf[--charPos] = digits[i & mask];
   265             i >>>= shift;
   266         } while (i != 0);
   267 
   268         return new String(buf, charPos, (32 - charPos));
   269     }
   270 
   271 
   272     final static char [] DigitTens = {
   273         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
   274         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
   275         '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
   276         '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
   277         '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
   278         '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
   279         '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
   280         '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
   281         '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
   282         '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
   283         } ;
   284 
   285     final static char [] DigitOnes = {
   286         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   287         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   288         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   289         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   290         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   291         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   292         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   293         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   294         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   295         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   296         } ;
   297 
   298         // I use the "invariant division by multiplication" trick to
   299         // accelerate Integer.toString.  In particular we want to
   300         // avoid division by 10.
   301         //
   302         // The "trick" has roughly the same performance characteristics
   303         // as the "classic" Integer.toString code on a non-JIT VM.
   304         // The trick avoids .rem and .div calls but has a longer code
   305         // path and is thus dominated by dispatch overhead.  In the
   306         // JIT case the dispatch overhead doesn't exist and the
   307         // "trick" is considerably faster than the classic code.
   308         //
   309         // TODO-FIXME: convert (x * 52429) into the equiv shift-add
   310         // sequence.
   311         //
   312         // RE:  Division by Invariant Integers using Multiplication
   313         //      T Gralund, P Montgomery
   314         //      ACM PLDI 1994
   315         //
   316 
   317     /**
   318      * Returns a {@code String} object representing the
   319      * specified integer. The argument is converted to signed decimal
   320      * representation and returned as a string, exactly as if the
   321      * argument and radix 10 were given as arguments to the {@link
   322      * #toString(int, int)} method.
   323      *
   324      * @param   i   an integer to be converted.
   325      * @return  a string representation of the argument in base&nbsp;10.
   326      */
   327     @JavaScriptBody(args = "i", body = "return i.toString();")
   328     public static String toString(int i) {
   329         if (i == Integer.MIN_VALUE)
   330             return "-2147483648";
   331         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
   332         char[] buf = new char[size];
   333         getChars(i, size, buf);
   334         return new String(buf, 0, size);
   335     }
   336 
   337     /**
   338      * Places characters representing the integer i into the
   339      * character array buf. The characters are placed into
   340      * the buffer backwards starting with the least significant
   341      * digit at the specified index (exclusive), and working
   342      * backwards from there.
   343      *
   344      * Will fail if i == Integer.MIN_VALUE
   345      */
   346     static void getChars(int i, int index, char[] buf) {
   347         int q, r;
   348         int charPos = index;
   349         char sign = 0;
   350 
   351         if (i < 0) {
   352             sign = '-';
   353             i = -i;
   354         }
   355 
   356         // Generate two digits per iteration
   357         while (i >= 65536) {
   358             q = i / 100;
   359         // really: r = i - (q * 100);
   360             r = i - ((q << 6) + (q << 5) + (q << 2));
   361             i = q;
   362             buf [--charPos] = DigitOnes[r];
   363             buf [--charPos] = DigitTens[r];
   364         }
   365 
   366         // Fall thru to fast mode for smaller numbers
   367         // assert(i <= 65536, i);
   368         for (;;) {
   369             q = (i * 52429) >>> (16+3);
   370             r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
   371             buf [--charPos] = digits [r];
   372             i = q;
   373             if (i == 0) break;
   374         }
   375         if (sign != 0) {
   376             buf [--charPos] = sign;
   377         }
   378     }
   379 
   380     final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
   381                                       99999999, 999999999, Integer.MAX_VALUE };
   382 
   383     // Requires positive x
   384     static int stringSize(int x) {
   385         for (int i=0; ; i++)
   386             if (x <= sizeTable[i])
   387                 return i+1;
   388     }
   389 
   390     /**
   391      * Parses the string argument as a signed integer in the radix
   392      * specified by the second argument. The characters in the string
   393      * must all be digits of the specified radix (as determined by
   394      * whether {@link java.lang.Character#digit(char, int)} returns a
   395      * nonnegative value), except that the first character may be an
   396      * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
   397      * indicate a negative value or an ASCII plus sign {@code '+'}
   398      * (<code>'&#92;u002B'</code>) to indicate a positive value. The
   399      * resulting integer value is returned.
   400      *
   401      * <p>An exception of type {@code NumberFormatException} is
   402      * thrown if any of the following situations occurs:
   403      * <ul>
   404      * <li>The first argument is {@code null} or is a string of
   405      * length zero.
   406      *
   407      * <li>The radix is either smaller than
   408      * {@link java.lang.Character#MIN_RADIX} or
   409      * larger than {@link java.lang.Character#MAX_RADIX}.
   410      *
   411      * <li>Any character of the string is not a digit of the specified
   412      * radix, except that the first character may be a minus sign
   413      * {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
   414      * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
   415      * string is longer than length 1.
   416      *
   417      * <li>The value represented by the string is not a value of type
   418      * {@code int}.
   419      * </ul>
   420      *
   421      * <p>Examples:
   422      * <blockquote><pre>
   423      * parseInt("0", 10) returns 0
   424      * parseInt("473", 10) returns 473
   425      * parseInt("+42", 10) returns 42
   426      * parseInt("-0", 10) returns 0
   427      * parseInt("-FF", 16) returns -255
   428      * parseInt("1100110", 2) returns 102
   429      * parseInt("2147483647", 10) returns 2147483647
   430      * parseInt("-2147483648", 10) returns -2147483648
   431      * parseInt("2147483648", 10) throws a NumberFormatException
   432      * parseInt("99", 8) throws a NumberFormatException
   433      * parseInt("Kona", 10) throws a NumberFormatException
   434      * parseInt("Kona", 27) returns 411787
   435      * </pre></blockquote>
   436      *
   437      * @param      s   the {@code String} containing the integer
   438      *                  representation to be parsed
   439      * @param      radix   the radix to be used while parsing {@code s}.
   440      * @return     the integer represented by the string argument in the
   441      *             specified radix.
   442      * @exception  NumberFormatException if the {@code String}
   443      *             does not contain a parsable {@code int}.
   444      */
   445     public static int parseInt(String s, int radix)
   446     throws NumberFormatException {
   447         double val = parseInt0(s, radix);
   448         if (Double.isNaN(val) || s.contains(".")) {
   449             throw new NumberFormatException("For input string: \"" + s + '\"');
   450         }
   451         return (int)val;
   452     }
   453 
   454     @JavaScriptBody(args={"s", "radix"}, body="return parseInt(s,radix);")
   455     private static native double parseInt0(String s, int radix);
   456 
   457     /**
   458      * Parses the string argument as a signed decimal integer. The
   459      * characters in the string must all be decimal digits, except
   460      * that the first character may be an ASCII minus sign {@code '-'}
   461      * (<code>'&#92;u002D'</code>) to indicate a negative value or an
   462      * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
   463      * indicate a positive value. The resulting integer value is
   464      * returned, exactly as if the argument and the radix 10 were
   465      * given as arguments to the {@link #parseInt(java.lang.String,
   466      * int)} method.
   467      *
   468      * @param s    a {@code String} containing the {@code int}
   469      *             representation to be parsed
   470      * @return     the integer value represented by the argument in decimal.
   471      * @exception  NumberFormatException  if the string does not contain a
   472      *               parsable integer.
   473      */
   474     public static int parseInt(String s) throws NumberFormatException {
   475         return parseInt(s,10);
   476     }
   477 
   478     /**
   479      * Returns an {@code Integer} object holding the value
   480      * extracted from the specified {@code String} when parsed
   481      * with the radix given by the second argument. The first argument
   482      * is interpreted as representing a signed integer in the radix
   483      * specified by the second argument, exactly as if the arguments
   484      * were given to the {@link #parseInt(java.lang.String, int)}
   485      * method. The result is an {@code Integer} object that
   486      * represents the integer value specified by the string.
   487      *
   488      * <p>In other words, this method returns an {@code Integer}
   489      * object equal to the value of:
   490      *
   491      * <blockquote>
   492      *  {@code new Integer(Integer.parseInt(s, radix))}
   493      * </blockquote>
   494      *
   495      * @param      s   the string to be parsed.
   496      * @param      radix the radix to be used in interpreting {@code s}
   497      * @return     an {@code Integer} object holding the value
   498      *             represented by the string argument in the specified
   499      *             radix.
   500      * @exception NumberFormatException if the {@code String}
   501      *            does not contain a parsable {@code int}.
   502      */
   503     public static Integer valueOf(String s, int radix) throws NumberFormatException {
   504         return Integer.valueOf(parseInt(s,radix));
   505     }
   506 
   507     /**
   508      * Returns an {@code Integer} object holding the
   509      * value of the specified {@code String}. The argument is
   510      * interpreted as representing a signed decimal integer, exactly
   511      * as if the argument were given to the {@link
   512      * #parseInt(java.lang.String)} method. The result is an
   513      * {@code Integer} object that represents the integer value
   514      * specified by the string.
   515      *
   516      * <p>In other words, this method returns an {@code Integer}
   517      * object equal to the value of:
   518      *
   519      * <blockquote>
   520      *  {@code new Integer(Integer.parseInt(s))}
   521      * </blockquote>
   522      *
   523      * @param      s   the string to be parsed.
   524      * @return     an {@code Integer} object holding the value
   525      *             represented by the string argument.
   526      * @exception  NumberFormatException  if the string cannot be parsed
   527      *             as an integer.
   528      */
   529     public static Integer valueOf(String s) throws NumberFormatException {
   530         return Integer.valueOf(parseInt(s, 10));
   531     }
   532 
   533     /**
   534      * Cache to support the object identity semantics of autoboxing for values between
   535      * -128 and 127 (inclusive) as required by JLS.
   536      *
   537      * The cache is initialized on first usage.  The size of the cache
   538      * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
   539      * During VM initialization, java.lang.Integer.IntegerCache.high property
   540      * may be set and saved in the private system properties in the
   541      * sun.misc.VM class.
   542      */
   543 
   544     private static class IntegerCache {
   545         static final int low = -128;
   546         static final int high;
   547         static final Integer cache[];
   548 
   549         static {
   550             // high value may be configured by property
   551             int h = 127;
   552             String integerCacheHighPropValue =
   553                 AbstractStringBuilder.getProperty("java.lang.Integer.IntegerCache.high");
   554             if (integerCacheHighPropValue != null) {
   555                 int i = parseInt(integerCacheHighPropValue);
   556                 i = Math.max(i, 127);
   557                 // Maximum array size is Integer.MAX_VALUE
   558                 h = Math.min(i, Integer.MAX_VALUE - (-low));
   559             }
   560             high = h;
   561 
   562             cache = new Integer[(high - low) + 1];
   563             int j = low;
   564             for(int k = 0; k < cache.length; k++)
   565                 cache[k] = new Integer(j++);
   566         }
   567 
   568         private IntegerCache() {}
   569     }
   570 
   571     /**
   572      * Returns an {@code Integer} instance representing the specified
   573      * {@code int} value.  If a new {@code Integer} instance is not
   574      * required, this method should generally be used in preference to
   575      * the constructor {@link #Integer(int)}, as this method is likely
   576      * to yield significantly better space and time performance by
   577      * caching frequently requested values.
   578      *
   579      * This method will always cache values in the range -128 to 127,
   580      * inclusive, and may cache other values outside of this range.
   581      *
   582      * @param  i an {@code int} value.
   583      * @return an {@code Integer} instance representing {@code i}.
   584      * @since  1.5
   585      */
   586     public static Integer valueOf(int i) {
   587         //assert IntegerCache.high >= 127;
   588         if (i >= IntegerCache.low && i <= IntegerCache.high)
   589             return IntegerCache.cache[i + (-IntegerCache.low)];
   590         return new Integer(i);
   591     }
   592 
   593     /**
   594      * The value of the {@code Integer}.
   595      *
   596      * @serial
   597      */
   598     private final int value;
   599 
   600     /**
   601      * Constructs a newly allocated {@code Integer} object that
   602      * represents the specified {@code int} value.
   603      *
   604      * @param   value   the value to be represented by the
   605      *                  {@code Integer} object.
   606      */
   607     public Integer(int value) {
   608         this.value = value;
   609     }
   610 
   611     /**
   612      * Constructs a newly allocated {@code Integer} object that
   613      * represents the {@code int} value indicated by the
   614      * {@code String} parameter. The string is converted to an
   615      * {@code int} value in exactly the manner used by the
   616      * {@code parseInt} method for radix 10.
   617      *
   618      * @param      s   the {@code String} to be converted to an
   619      *                 {@code Integer}.
   620      * @exception  NumberFormatException  if the {@code String} does not
   621      *               contain a parsable integer.
   622      * @see        java.lang.Integer#parseInt(java.lang.String, int)
   623      */
   624     public Integer(String s) throws NumberFormatException {
   625         this.value = parseInt(s, 10);
   626     }
   627 
   628     /**
   629      * Returns the value of this {@code Integer} as a
   630      * {@code byte}.
   631      */
   632     public byte byteValue() {
   633         return (byte)value;
   634     }
   635 
   636     /**
   637      * Returns the value of this {@code Integer} as a
   638      * {@code short}.
   639      */
   640     public short shortValue() {
   641         return (short)value;
   642     }
   643 
   644     /**
   645      * Returns the value of this {@code Integer} as an
   646      * {@code int}.
   647      */
   648     public int intValue() {
   649         return value;
   650     }
   651 
   652     /**
   653      * Returns the value of this {@code Integer} as a
   654      * {@code long}.
   655      */
   656     public long longValue() {
   657         return (long)value;
   658     }
   659 
   660     /**
   661      * Returns the value of this {@code Integer} as a
   662      * {@code float}.
   663      */
   664     public float floatValue() {
   665         return (float)value;
   666     }
   667 
   668     /**
   669      * Returns the value of this {@code Integer} as a
   670      * {@code double}.
   671      */
   672     public double doubleValue() {
   673         return (double)value;
   674     }
   675 
   676     /**
   677      * Returns a {@code String} object representing this
   678      * {@code Integer}'s value. The value is converted to signed
   679      * decimal representation and returned as a string, exactly as if
   680      * the integer value were given as an argument to the {@link
   681      * java.lang.Integer#toString(int)} method.
   682      *
   683      * @return  a string representation of the value of this object in
   684      *          base&nbsp;10.
   685      */
   686     public String toString() {
   687         return toString(value);
   688     }
   689 
   690     /**
   691      * Returns a hash code for this {@code Integer}.
   692      *
   693      * @return  a hash code value for this object, equal to the
   694      *          primitive {@code int} value represented by this
   695      *          {@code Integer} object.
   696      */
   697     public int hashCode() {
   698         return value;
   699     }
   700 
   701     /**
   702      * Compares this object to the specified object.  The result is
   703      * {@code true} if and only if the argument is not
   704      * {@code null} and is an {@code Integer} object that
   705      * contains the same {@code int} value as this object.
   706      *
   707      * @param   obj   the object to compare with.
   708      * @return  {@code true} if the objects are the same;
   709      *          {@code false} otherwise.
   710      */
   711     public boolean equals(Object obj) {
   712         if (obj instanceof Integer) {
   713             return value == ((Integer)obj).intValue();
   714         }
   715         return false;
   716     }
   717 
   718     /**
   719      * Determines the integer value of the system property with the
   720      * specified name.
   721      *
   722      * <p>The first argument is treated as the name of a system property.
   723      * System properties are accessible through the
   724      * {@link java.lang.System#getProperty(java.lang.String)} method. The
   725      * string value of this property is then interpreted as an integer
   726      * value and an {@code Integer} object representing this value is
   727      * returned. Details of possible numeric formats can be found with
   728      * the definition of {@code getProperty}.
   729      *
   730      * <p>If there is no property with the specified name, if the specified name
   731      * is empty or {@code null}, or if the property does not have
   732      * the correct numeric format, then {@code null} is returned.
   733      *
   734      * <p>In other words, this method returns an {@code Integer}
   735      * object equal to the value of:
   736      *
   737      * <blockquote>
   738      *  {@code getInteger(nm, null)}
   739      * </blockquote>
   740      *
   741      * @param   nm   property name.
   742      * @return  the {@code Integer} value of the property.
   743      * @see     java.lang.System#getProperty(java.lang.String)
   744      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
   745      */
   746     public static Integer getInteger(String nm) {
   747         return getInteger(nm, null);
   748     }
   749 
   750     /**
   751      * Determines the integer value of the system property with the
   752      * specified name.
   753      *
   754      * <p>The first argument is treated as the name of a system property.
   755      * System properties are accessible through the {@link
   756      * java.lang.System#getProperty(java.lang.String)} method. The
   757      * string value of this property is then interpreted as an integer
   758      * value and an {@code Integer} object representing this value is
   759      * returned. Details of possible numeric formats can be found with
   760      * the definition of {@code getProperty}.
   761      *
   762      * <p>The second argument is the default value. An {@code Integer} object
   763      * that represents the value of the second argument is returned if there
   764      * is no property of the specified name, if the property does not have
   765      * the correct numeric format, or if the specified name is empty or
   766      * {@code null}.
   767      *
   768      * <p>In other words, this method returns an {@code Integer} object
   769      * equal to the value of:
   770      *
   771      * <blockquote>
   772      *  {@code getInteger(nm, new Integer(val))}
   773      * </blockquote>
   774      *
   775      * but in practice it may be implemented in a manner such as:
   776      *
   777      * <blockquote><pre>
   778      * Integer result = getInteger(nm, null);
   779      * return (result == null) ? new Integer(val) : result;
   780      * </pre></blockquote>
   781      *
   782      * to avoid the unnecessary allocation of an {@code Integer}
   783      * object when the default value is not needed.
   784      *
   785      * @param   nm   property name.
   786      * @param   val   default value.
   787      * @return  the {@code Integer} value of the property.
   788      * @see     java.lang.System#getProperty(java.lang.String)
   789      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
   790      */
   791     public static Integer getInteger(String nm, int val) {
   792         Integer result = getInteger(nm, null);
   793         return (result == null) ? Integer.valueOf(val) : result;
   794     }
   795 
   796     /**
   797      * Returns the integer value of the system property with the
   798      * specified name.  The first argument is treated as the name of a
   799      * system property.  System properties are accessible through the
   800      * {@link java.lang.System#getProperty(java.lang.String)} method.
   801      * The string value of this property is then interpreted as an
   802      * integer value, as per the {@code Integer.decode} method,
   803      * and an {@code Integer} object representing this value is
   804      * returned.
   805      *
   806      * <ul><li>If the property value begins with the two ASCII characters
   807      *         {@code 0x} or the ASCII character {@code #}, not
   808      *      followed by a minus sign, then the rest of it is parsed as a
   809      *      hexadecimal integer exactly as by the method
   810      *      {@link #valueOf(java.lang.String, int)} with radix 16.
   811      * <li>If the property value begins with the ASCII character
   812      *     {@code 0} followed by another character, it is parsed as an
   813      *     octal integer exactly as by the method
   814      *     {@link #valueOf(java.lang.String, int)} with radix 8.
   815      * <li>Otherwise, the property value is parsed as a decimal integer
   816      * exactly as by the method {@link #valueOf(java.lang.String, int)}
   817      * with radix 10.
   818      * </ul>
   819      *
   820      * <p>The second argument is the default value. The default value is
   821      * returned if there is no property of the specified name, if the
   822      * property does not have the correct numeric format, or if the
   823      * specified name is empty or {@code null}.
   824      *
   825      * @param   nm   property name.
   826      * @param   val   default value.
   827      * @return  the {@code Integer} value of the property.
   828      * @see     java.lang.System#getProperty(java.lang.String)
   829      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
   830      * @see java.lang.Integer#decode
   831      */
   832     public static Integer getInteger(String nm, Integer val) {
   833         String v = null;
   834         try {
   835             v = AbstractStringBuilder.getProperty(nm);
   836         } catch (IllegalArgumentException e) {
   837         } catch (NullPointerException e) {
   838         }
   839         if (v != null) {
   840             try {
   841                 return Integer.decode(v);
   842             } catch (NumberFormatException e) {
   843             }
   844         }
   845         return val;
   846     }
   847 
   848     /**
   849      * Decodes a {@code String} into an {@code Integer}.
   850      * Accepts decimal, hexadecimal, and octal numbers given
   851      * by the following grammar:
   852      *
   853      * <blockquote>
   854      * <dl>
   855      * <dt><i>DecodableString:</i>
   856      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
   857      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
   858      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
   859      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
   860      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
   861      * <p>
   862      * <dt><i>Sign:</i>
   863      * <dd>{@code -}
   864      * <dd>{@code +}
   865      * </dl>
   866      * </blockquote>
   867      *
   868      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
   869      * are as defined in section 3.10.1 of
   870      * <cite>The Java&trade; Language Specification</cite>,
   871      * except that underscores are not accepted between digits.
   872      *
   873      * <p>The sequence of characters following an optional
   874      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
   875      * "{@code #}", or leading zero) is parsed as by the {@code
   876      * Integer.parseInt} method with the indicated radix (10, 16, or
   877      * 8).  This sequence of characters must represent a positive
   878      * value or a {@link NumberFormatException} will be thrown.  The
   879      * result is negated if first character of the specified {@code
   880      * String} is the minus sign.  No whitespace characters are
   881      * permitted in the {@code String}.
   882      *
   883      * @param     nm the {@code String} to decode.
   884      * @return    an {@code Integer} object holding the {@code int}
   885      *             value represented by {@code nm}
   886      * @exception NumberFormatException  if the {@code String} does not
   887      *            contain a parsable integer.
   888      * @see java.lang.Integer#parseInt(java.lang.String, int)
   889      */
   890     public static Integer decode(String nm) throws NumberFormatException {
   891         int radix = 10;
   892         int index = 0;
   893         boolean negative = false;
   894         Integer result;
   895 
   896         if (nm.length() == 0)
   897             throw new NumberFormatException("Zero length string");
   898         char firstChar = nm.charAt(0);
   899         // Handle sign, if present
   900         if (firstChar == '-') {
   901             negative = true;
   902             index++;
   903         } else if (firstChar == '+')
   904             index++;
   905 
   906         // Handle radix specifier, if present
   907         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
   908             index += 2;
   909             radix = 16;
   910         }
   911         else if (nm.startsWith("#", index)) {
   912             index ++;
   913             radix = 16;
   914         }
   915         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
   916             index ++;
   917             radix = 8;
   918         }
   919 
   920         if (nm.startsWith("-", index) || nm.startsWith("+", index))
   921             throw new NumberFormatException("Sign character in wrong position");
   922 
   923         try {
   924             result = Integer.valueOf(nm.substring(index), radix);
   925             result = negative ? Integer.valueOf(-result.intValue()) : result;
   926         } catch (NumberFormatException e) {
   927             // If number is Integer.MIN_VALUE, we'll end up here. The next line
   928             // handles this case, and causes any genuine format error to be
   929             // rethrown.
   930             String constant = negative ? ("-" + nm.substring(index))
   931                                        : nm.substring(index);
   932             result = Integer.valueOf(constant, radix);
   933         }
   934         return result;
   935     }
   936 
   937     /**
   938      * Compares two {@code Integer} objects numerically.
   939      *
   940      * @param   anotherInteger   the {@code Integer} to be compared.
   941      * @return  the value {@code 0} if this {@code Integer} is
   942      *          equal to the argument {@code Integer}; a value less than
   943      *          {@code 0} if this {@code Integer} is numerically less
   944      *          than the argument {@code Integer}; and a value greater
   945      *          than {@code 0} if this {@code Integer} is numerically
   946      *           greater than the argument {@code Integer} (signed
   947      *           comparison).
   948      * @since   1.2
   949      */
   950     public int compareTo(Integer anotherInteger) {
   951         return compare(this.value, anotherInteger.value);
   952     }
   953 
   954     /**
   955      * Compares two {@code int} values numerically.
   956      * The value returned is identical to what would be returned by:
   957      * <pre>
   958      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
   959      * </pre>
   960      *
   961      * @param  x the first {@code int} to compare
   962      * @param  y the second {@code int} to compare
   963      * @return the value {@code 0} if {@code x == y};
   964      *         a value less than {@code 0} if {@code x < y}; and
   965      *         a value greater than {@code 0} if {@code x > y}
   966      * @since 1.7
   967      */
   968     public static int compare(int x, int y) {
   969         return (x < y) ? -1 : ((x == y) ? 0 : 1);
   970     }
   971 
   972 
   973     // Bit twiddling
   974 
   975     /**
   976      * The number of bits used to represent an {@code int} value in two's
   977      * complement binary form.
   978      *
   979      * @since 1.5
   980      */
   981     public static final int SIZE = 32;
   982 
   983     /**
   984      * Returns an {@code int} value with at most a single one-bit, in the
   985      * position of the highest-order ("leftmost") one-bit in the specified
   986      * {@code int} value.  Returns zero if the specified value has no
   987      * one-bits in its two's complement binary representation, that is, if it
   988      * is equal to zero.
   989      *
   990      * @return an {@code int} value with a single one-bit, in the position
   991      *     of the highest-order one-bit in the specified value, or zero if
   992      *     the specified value is itself equal to zero.
   993      * @since 1.5
   994      */
   995     public static int highestOneBit(int i) {
   996         // HD, Figure 3-1
   997         i |= (i >>  1);
   998         i |= (i >>  2);
   999         i |= (i >>  4);
  1000         i |= (i >>  8);
  1001         i |= (i >> 16);
  1002         return i - (i >>> 1);
  1003     }
  1004 
  1005     /**
  1006      * Returns an {@code int} value with at most a single one-bit, in the
  1007      * position of the lowest-order ("rightmost") one-bit in the specified
  1008      * {@code int} value.  Returns zero if the specified value has no
  1009      * one-bits in its two's complement binary representation, that is, if it
  1010      * is equal to zero.
  1011      *
  1012      * @return an {@code int} value with a single one-bit, in the position
  1013      *     of the lowest-order one-bit in the specified value, or zero if
  1014      *     the specified value is itself equal to zero.
  1015      * @since 1.5
  1016      */
  1017     public static int lowestOneBit(int i) {
  1018         // HD, Section 2-1
  1019         return i & -i;
  1020     }
  1021 
  1022     /**
  1023      * Returns the number of zero bits preceding the highest-order
  1024      * ("leftmost") one-bit in the two's complement binary representation
  1025      * of the specified {@code int} value.  Returns 32 if the
  1026      * specified value has no one-bits in its two's complement representation,
  1027      * in other words if it is equal to zero.
  1028      *
  1029      * <p>Note that this method is closely related to the logarithm base 2.
  1030      * For all positive {@code int} values x:
  1031      * <ul>
  1032      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
  1033      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
  1034      * </ul>
  1035      *
  1036      * @return the number of zero bits preceding the highest-order
  1037      *     ("leftmost") one-bit in the two's complement binary representation
  1038      *     of the specified {@code int} value, or 32 if the value
  1039      *     is equal to zero.
  1040      * @since 1.5
  1041      */
  1042     public static int numberOfLeadingZeros(int i) {
  1043         // HD, Figure 5-6
  1044         if (i == 0)
  1045             return 32;
  1046         int n = 1;
  1047         if (i >>> 16 == 0) { n += 16; i <<= 16; }
  1048         if (i >>> 24 == 0) { n +=  8; i <<=  8; }
  1049         if (i >>> 28 == 0) { n +=  4; i <<=  4; }
  1050         if (i >>> 30 == 0) { n +=  2; i <<=  2; }
  1051         n -= i >>> 31;
  1052         return n;
  1053     }
  1054 
  1055     /**
  1056      * Returns the number of zero bits following the lowest-order ("rightmost")
  1057      * one-bit in the two's complement binary representation of the specified
  1058      * {@code int} value.  Returns 32 if the specified value has no
  1059      * one-bits in its two's complement representation, in other words if it is
  1060      * equal to zero.
  1061      *
  1062      * @return the number of zero bits following the lowest-order ("rightmost")
  1063      *     one-bit in the two's complement binary representation of the
  1064      *     specified {@code int} value, or 32 if the value is equal
  1065      *     to zero.
  1066      * @since 1.5
  1067      */
  1068     public static int numberOfTrailingZeros(int i) {
  1069         // HD, Figure 5-14
  1070         int y;
  1071         if (i == 0) return 32;
  1072         int n = 31;
  1073         y = i <<16; if (y != 0) { n = n -16; i = y; }
  1074         y = i << 8; if (y != 0) { n = n - 8; i = y; }
  1075         y = i << 4; if (y != 0) { n = n - 4; i = y; }
  1076         y = i << 2; if (y != 0) { n = n - 2; i = y; }
  1077         return n - ((i << 1) >>> 31);
  1078     }
  1079 
  1080     /**
  1081      * Returns the number of one-bits in the two's complement binary
  1082      * representation of the specified {@code int} value.  This function is
  1083      * sometimes referred to as the <i>population count</i>.
  1084      *
  1085      * @return the number of one-bits in the two's complement binary
  1086      *     representation of the specified {@code int} value.
  1087      * @since 1.5
  1088      */
  1089     public static int bitCount(int i) {
  1090         // HD, Figure 5-2
  1091         i = i - ((i >>> 1) & 0x55555555);
  1092         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
  1093         i = (i + (i >>> 4)) & 0x0f0f0f0f;
  1094         i = i + (i >>> 8);
  1095         i = i + (i >>> 16);
  1096         return i & 0x3f;
  1097     }
  1098 
  1099     /**
  1100      * Returns the value obtained by rotating the two's complement binary
  1101      * representation of the specified {@code int} value left by the
  1102      * specified number of bits.  (Bits shifted out of the left hand, or
  1103      * high-order, side reenter on the right, or low-order.)
  1104      *
  1105      * <p>Note that left rotation with a negative distance is equivalent to
  1106      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
  1107      * distance)}.  Note also that rotation by any multiple of 32 is a
  1108      * no-op, so all but the last five bits of the rotation distance can be
  1109      * ignored, even if the distance is negative: {@code rotateLeft(val,
  1110      * distance) == rotateLeft(val, distance & 0x1F)}.
  1111      *
  1112      * @return the value obtained by rotating the two's complement binary
  1113      *     representation of the specified {@code int} value left by the
  1114      *     specified number of bits.
  1115      * @since 1.5
  1116      */
  1117     public static int rotateLeft(int i, int distance) {
  1118         return (i << distance) | (i >>> -distance);
  1119     }
  1120 
  1121     /**
  1122      * Returns the value obtained by rotating the two's complement binary
  1123      * representation of the specified {@code int} value right by the
  1124      * specified number of bits.  (Bits shifted out of the right hand, or
  1125      * low-order, side reenter on the left, or high-order.)
  1126      *
  1127      * <p>Note that right rotation with a negative distance is equivalent to
  1128      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
  1129      * distance)}.  Note also that rotation by any multiple of 32 is a
  1130      * no-op, so all but the last five bits of the rotation distance can be
  1131      * ignored, even if the distance is negative: {@code rotateRight(val,
  1132      * distance) == rotateRight(val, distance & 0x1F)}.
  1133      *
  1134      * @return the value obtained by rotating the two's complement binary
  1135      *     representation of the specified {@code int} value right by the
  1136      *     specified number of bits.
  1137      * @since 1.5
  1138      */
  1139     public static int rotateRight(int i, int distance) {
  1140         return (i >>> distance) | (i << -distance);
  1141     }
  1142 
  1143     /**
  1144      * Returns the value obtained by reversing the order of the bits in the
  1145      * two's complement binary representation of the specified {@code int}
  1146      * value.
  1147      *
  1148      * @return the value obtained by reversing order of the bits in the
  1149      *     specified {@code int} value.
  1150      * @since 1.5
  1151      */
  1152     public static int reverse(int i) {
  1153         // HD, Figure 7-1
  1154         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
  1155         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
  1156         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
  1157         i = (i << 24) | ((i & 0xff00) << 8) |
  1158             ((i >>> 8) & 0xff00) | (i >>> 24);
  1159         return i;
  1160     }
  1161 
  1162     /**
  1163      * Returns the signum function of the specified {@code int} value.  (The
  1164      * return value is -1 if the specified value is negative; 0 if the
  1165      * specified value is zero; and 1 if the specified value is positive.)
  1166      *
  1167      * @return the signum function of the specified {@code int} value.
  1168      * @since 1.5
  1169      */
  1170     public static int signum(int i) {
  1171         // HD, Section 2-7
  1172         return (i >> 31) | (-i >>> 31);
  1173     }
  1174 
  1175     /**
  1176      * Returns the value obtained by reversing the order of the bytes in the
  1177      * two's complement representation of the specified {@code int} value.
  1178      *
  1179      * @return the value obtained by reversing the bytes in the specified
  1180      *     {@code int} value.
  1181      * @since 1.5
  1182      */
  1183     public static int reverseBytes(int i) {
  1184         return ((i >>> 24)           ) |
  1185                ((i >>   8) &   0xFF00) |
  1186                ((i <<   8) & 0xFF0000) |
  1187                ((i << 24));
  1188     }
  1189 
  1190     /** use serialVersionUID from JDK 1.0.2 for interoperability */
  1191     private static final long serialVersionUID = 1360826667806852920L;
  1192 }