1 /*
   2  * Copyright 1994-2006 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.lang;
  27 
  28 import java.util.Properties;
  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     public static String toString(int i) {
 328         if (i == Integer.MIN_VALUE)
 329             return "-2147483648";
 330         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
 331         char[] buf = new char[size];
 332         getChars(i, size, buf);
 333         return new String(0, size, buf);
 334     }
 335 
 336     /**
 337      * Places characters representing the integer i into the
 338      * character array buf. The characters are placed into
 339      * the buffer backwards starting with the least significant
 340      * digit at the specified index (exclusive), and working
 341      * backwards from there.
 342      *
 343      * Will fail if i == Integer.MIN_VALUE
 344      */
 345     static void getChars(int i, int index, char[] buf) {
 346         int q, r;
 347         int charPos = index;
 348         char sign = 0;
 349 
 350         if (i < 0) {
 351             sign = '-';
 352             i = -i;
 353         }
 354 
 355         // Generate two digits per iteration
 356         while (i >= 65536) {
 357             q = i / 100;
 358         // really: r = i - (q * 100);
 359             r = i - ((q << 6) + (q << 5) + (q << 2));
 360             i = q;
 361             buf [--charPos] = DigitOnes[r];
 362             buf [--charPos] = DigitTens[r];
 363         }
 364 
 365         // Fall thru to fast mode for smaller numbers
 366         // assert(i <= 65536, i);
 367         for (;;) {
 368             q = (i * 52429) >>> (16+3);
 369             r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
 370             buf [--charPos] = digits [r];
 371             i = q;
 372             if (i == 0) break;
 373         }
 374         if (sign != 0) {
 375             buf [--charPos] = sign;
 376         }
 377     }
 378 
 379     final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
 380                                       99999999, 999999999, Integer.MAX_VALUE };
 381 
 382     // Requires positive x
 383     static int stringSize(int x) {
 384         for (int i=0; ; i++)
 385             if (x <= sizeTable[i])
 386                 return i+1;
 387     }
 388 
 389     /**
 390      * Parses the string argument as a signed integer in the radix
 391      * specified by the second argument. The characters in the string
 392      * must all be digits of the specified radix (as determined by
 393      * whether {@link java.lang.Character#digit(char, int)} returns a
 394      * nonnegative value), except that the first character may be an
 395      * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
 396      * indicate a negative value or an ASCII plus sign {@code '+'}
 397      * (<code>'&#92;u002B'</code>) to indicate a positive value. The
 398      * resulting integer value is returned.
 399      *
 400      * <p>An exception of type {@code NumberFormatException} is
 401      * thrown if any of the following situations occurs:
 402      * <ul>
 403      * <li>The first argument is {@code null} or is a string of
 404      * length zero.
 405      *
 406      * <li>The radix is either smaller than
 407      * {@link java.lang.Character#MIN_RADIX} or
 408      * larger than {@link java.lang.Character#MAX_RADIX}.
 409      *
 410      * <li>Any character of the string is not a digit of the specified
 411      * radix, except that the first character may be a minus sign
 412      * {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
 413      * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
 414      * string is longer than length 1.
 415      *
 416      * <li>The value represented by the string is not a value of type
 417      * {@code int}.
 418      * </ul>
 419      *
 420      * <p>Examples:
 421      * <blockquote><pre>
 422      * parseInt("0", 10) returns 0
 423      * parseInt("473", 10) returns 473
 424      * parseInt("+42", 10) returns 42
 425      * parseInt("-0", 10) returns 0
 426      * parseInt("-FF", 16) returns -255
 427      * parseInt("1100110", 2) returns 102
 428      * parseInt("2147483647", 10) returns 2147483647
 429      * parseInt("-2147483648", 10) returns -2147483648
 430      * parseInt("2147483648", 10) throws a NumberFormatException
 431      * parseInt("99", 8) throws a NumberFormatException
 432      * parseInt("Kona", 10) throws a NumberFormatException
 433      * parseInt("Kona", 27) returns 411787
 434      * </pre></blockquote>
 435      *
 436      * @param      s   the {@code String} containing the integer
 437      *                  representation to be parsed
 438      * @param      radix   the radix to be used while parsing {@code s}.
 439      * @return     the integer represented by the string argument in the
 440      *             specified radix.
 441      * @exception  NumberFormatException if the {@code String}
 442      *             does not contain a parsable {@code int}.
 443      */
 444     public static int parseInt(String s, int radix)
 445                 throws NumberFormatException
 446     {
 447         /*
 448          * WARNING: This method may be invoked early during VM initialization
 449          * before IntegerCache is initialized. Care must be taken to not use
 450          * the valueOf method.
 451          */
 452 
 453         if (s == null) {
 454             throw new NumberFormatException("null");
 455         }
 456 
 457         if (radix < Character.MIN_RADIX) {
 458             throw new NumberFormatException("radix " + radix +
 459                                             " less than Character.MIN_RADIX");
 460         }
 461 
 462         if (radix > Character.MAX_RADIX) {
 463             throw new NumberFormatException("radix " + radix +
 464                                             " greater than Character.MAX_RADIX");
 465         }
 466 
 467         int result = 0;
 468         boolean negative = false;
 469         int i = 0, len = s.length();
 470         int limit = -Integer.MAX_VALUE;
 471         int multmin;
 472         int digit;
 473 
 474         if (len > 0) {
 475             char firstChar = s.charAt(0);
 476             if (firstChar < '0') { // Possible leading "+" or "-"
 477                 if (firstChar == '-') {
 478                     negative = true;
 479                     limit = Integer.MIN_VALUE;
 480                 } else if (firstChar != '+')
 481                     throw NumberFormatException.forInputString(s);
 482 
 483                 if (len == 1) // Cannot have lone "+" or "-"
 484                     throw NumberFormatException.forInputString(s);
 485                 i++;
 486             }
 487             multmin = limit / radix;
 488             while (i < len) {
 489                 // Accumulating negatively avoids surprises near MAX_VALUE
 490                 digit = Character.digit(s.charAt(i++),radix);
 491                 if (digit < 0) {
 492                     throw NumberFormatException.forInputString(s);
 493                 }
 494                 if (result < multmin) {
 495                     throw NumberFormatException.forInputString(s);
 496                 }
 497                 result *= radix;
 498                 if (result < limit + digit) {
 499                     throw NumberFormatException.forInputString(s);
 500                 }
 501                 result -= digit;
 502             }
 503         } else {
 504             throw NumberFormatException.forInputString(s);
 505         }
 506         return negative ? result : -result;
 507     }
 508 
 509     /**
 510      * Parses the string argument as a signed decimal integer. The
 511      * characters in the string must all be decimal digits, except
 512      * that the first character may be an ASCII minus sign {@code '-'}
 513      * (<code>'&#92;u002D'</code>) to indicate a negative value or an
 514      * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
 515      * indicate a positive value. The resulting integer value is
 516      * returned, exactly as if the argument and the radix 10 were
 517      * given as arguments to the {@link #parseInt(java.lang.String,
 518      * int)} method.
 519      *
 520      * @param s    a {@code String} containing the {@code int}
 521      *             representation to be parsed
 522      * @return     the integer value represented by the argument in decimal.
 523      * @exception  NumberFormatException  if the string does not contain a
 524      *               parsable integer.
 525      */
 526     public static int parseInt(String s) throws NumberFormatException {
 527         return parseInt(s,10);
 528     }
 529 
 530     /**
 531      * Returns an {@code Integer} object holding the value
 532      * extracted from the specified {@code String} when parsed
 533      * with the radix given by the second argument. The first argument
 534      * is interpreted as representing a signed integer in the radix
 535      * specified by the second argument, exactly as if the arguments
 536      * were given to the {@link #parseInt(java.lang.String, int)}
 537      * method. The result is an {@code Integer} object that
 538      * represents the integer value specified by the string.
 539      *
 540      * <p>In other words, this method returns an {@code Integer}
 541      * object equal to the value of:
 542      *
 543      * <blockquote>
 544      *  {@code new Integer(Integer.parseInt(s, radix))}
 545      * </blockquote>
 546      *
 547      * @param      s   the string to be parsed.
 548      * @param      radix the radix to be used in interpreting {@code s}
 549      * @return     an {@code Integer} object holding the value
 550      *             represented by the string argument in the specified
 551      *             radix.
 552      * @exception NumberFormatException if the {@code String}
 553      *            does not contain a parsable {@code int}.
 554      */
 555     public static Integer valueOf(String s, int radix) throws NumberFormatException {
 556         return Integer.valueOf(parseInt(s,radix));
 557     }
 558 
 559     /**
 560      * Returns an {@code Integer} object holding the
 561      * value of the specified {@code String}. The argument is
 562      * interpreted as representing a signed decimal integer, exactly
 563      * as if the argument were given to the {@link
 564      * #parseInt(java.lang.String)} method. The result is an
 565      * {@code Integer} object that represents the integer value
 566      * specified by the string.
 567      *
 568      * <p>In other words, this method returns an {@code Integer}
 569      * object equal to the value of:
 570      *
 571      * <blockquote>
 572      *  {@code new Integer(Integer.parseInt(s))}
 573      * </blockquote>
 574      *
 575      * @param      s   the string to be parsed.
 576      * @return     an {@code Integer} object holding the value
 577      *             represented by the string argument.
 578      * @exception  NumberFormatException  if the string cannot be parsed
 579      *             as an integer.
 580      */
 581     public static Integer valueOf(String s) throws NumberFormatException {
 582         return Integer.valueOf(parseInt(s, 10));
 583     }
 584 
 585     /**
 586      * Cache to support the object identity semantics of autoboxing for values between
 587      * -128 and 127 (inclusive) as required by JLS.
 588      *
 589      * The cache is initialized on first usage. During VM initialization the
 590      * getAndRemoveCacheProperties method may be used to get and remove any system
 591      * properites that configure the cache size. At this time, the size of the
 592      * cache may be controlled by the -XX:AutoBoxCacheMax=<size> option.
 593      */
 594 
 595     // value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
 596     private static String integerCacheHighPropValue;
 597 
 598     static void getAndRemoveCacheProperties() {
 599         if (!sun.misc.VM.isBooted()) {
 600             Properties props = System.getProperties();
 601             integerCacheHighPropValue =
 602                 (String)props.remove("java.lang.Integer.IntegerCache.high");
 603             if (integerCacheHighPropValue != null)
 604                 System.setProperties(props);  // remove from system props
 605         }
 606     }
 607 
 608     private static class IntegerCache {
 609         static final int low = -128;
 610         static final int high;
 611         static final Integer cache[];
 612 
 613         static {
 614             // high value may be configured by property
 615             int h = 127;
 616             if (integerCacheHighPropValue != null) {
 617                 int i = parseInt(integerCacheHighPropValue);
 618                 i = Math.max(i, 127);
 619                 // Maximum array size is Integer.MAX_VALUE
 620                 h = Math.min(i, Integer.MAX_VALUE - (-low));
 621             }
 622             high = h;
 623 
 624             cache = new Integer[(high - low) + 1];
 625             int j = low;
 626             for(int k = 0; k < cache.length; k++)
 627                 cache[k] = new Integer(j++);
 628         }
 629 
 630         private IntegerCache() {}
 631     }
 632 
 633     /**
 634      * Returns an {@code Integer} instance representing the specified
 635      * {@code int} value.  If a new {@code Integer} instance is not
 636      * required, this method should generally be used in preference to
 637      * the constructor {@link #Integer(int)}, as this method is likely
 638      * to yield significantly better space and time performance by
 639      * caching frequently requested values.
 640      *
 641      * @param  i an {@code int} value.
 642      * @return an {@code Integer} instance representing {@code i}.
 643      * @since  1.5
 644      */
 645     public static Integer valueOf(int i) {
 646         assert IntegerCache.high >= 127;
 647         if (i >= IntegerCache.low && i <= IntegerCache.high)
 648             return IntegerCache.cache[i + (-IntegerCache.low)];
 649         return new Integer(i);
 650     }
 651 
 652     /**
 653      * The value of the {@code Integer}.
 654      *
 655      * @serial
 656      */
 657     private final int value;
 658 
 659     /**
 660      * Constructs a newly allocated {@code Integer} object that
 661      * represents the specified {@code int} value.
 662      *
 663      * @param   value   the value to be represented by the
 664      *                  {@code Integer} object.
 665      */
 666     public Integer(int value) {
 667         this.value = value;
 668     }
 669 
 670     /**
 671      * Constructs a newly allocated {@code Integer} object that
 672      * represents the {@code int} value indicated by the
 673      * {@code String} parameter. The string is converted to an
 674      * {@code int} value in exactly the manner used by the
 675      * {@code parseInt} method for radix 10.
 676      *
 677      * @param      s   the {@code String} to be converted to an
 678      *                 {@code Integer}.
 679      * @exception  NumberFormatException  if the {@code String} does not
 680      *               contain a parsable integer.
 681      * @see        java.lang.Integer#parseInt(java.lang.String, int)
 682      */
 683     public Integer(String s) throws NumberFormatException {
 684         this.value = parseInt(s, 10);
 685     }
 686 
 687     /**
 688      * Returns the value of this {@code Integer} as a
 689      * {@code byte}.
 690      */
 691     public byte byteValue() {
 692         return (byte)value;
 693     }
 694 
 695     /**
 696      * Returns the value of this {@code Integer} as a
 697      * {@code short}.
 698      */
 699     public short shortValue() {
 700         return (short)value;
 701     }
 702 
 703     /**
 704      * Returns the value of this {@code Integer} as an
 705      * {@code int}.
 706      */
 707     public int intValue() {
 708         return value;
 709     }
 710 
 711     /**
 712      * Returns the value of this {@code Integer} as a
 713      * {@code long}.
 714      */
 715     public long longValue() {
 716         return (long)value;
 717     }
 718 
 719     /**
 720      * Returns the value of this {@code Integer} as a
 721      * {@code float}.
 722      */
 723     public float floatValue() {
 724         return (float)value;
 725     }
 726 
 727     /**
 728      * Returns the value of this {@code Integer} as a
 729      * {@code double}.
 730      */
 731     public double doubleValue() {
 732         return (double)value;
 733     }
 734 
 735     /**
 736      * Returns a {@code String} object representing this
 737      * {@code Integer}'s value. The value is converted to signed
 738      * decimal representation and returned as a string, exactly as if
 739      * the integer value were given as an argument to the {@link
 740      * java.lang.Integer#toString(int)} method.
 741      *
 742      * @return  a string representation of the value of this object in
 743      *          base&nbsp;10.
 744      */
 745     public String toString() {
 746         return String.valueOf(value);
 747     }
 748 
 749     /**
 750      * Returns a hash code for this {@code Integer}.
 751      *
 752      * @return  a hash code value for this object, equal to the
 753      *          primitive {@code int} value represented by this
 754      *          {@code Integer} object.
 755      */
 756     public int hashCode() {
 757         return value;
 758     }
 759 
 760     /**
 761      * Compares this object to the specified object.  The result is
 762      * {@code true} if and only if the argument is not
 763      * {@code null} and is an {@code Integer} object that
 764      * contains the same {@code int} value as this object.
 765      *
 766      * @param   obj   the object to compare with.
 767      * @return  {@code true} if the objects are the same;
 768      *          {@code false} otherwise.
 769      */
 770     public boolean equals(Object obj) {
 771         if (obj instanceof Integer) {
 772             return value == ((Integer)obj).intValue();
 773         }
 774         return false;
 775     }
 776 
 777     /**
 778      * Determines the integer value of the system property with the
 779      * specified name.
 780      *
 781      * <p>The first argument is treated as the name of a system property.
 782      * System properties are accessible through the
 783      * {@link java.lang.System#getProperty(java.lang.String)} method. The
 784      * string value of this property is then interpreted as an integer
 785      * value and an {@code Integer} object representing this value is
 786      * returned. Details of possible numeric formats can be found with
 787      * the definition of {@code getProperty}.
 788      *
 789      * <p>If there is no property with the specified name, if the specified name
 790      * is empty or {@code null}, or if the property does not have
 791      * the correct numeric format, then {@code null} is returned.
 792      *
 793      * <p>In other words, this method returns an {@code Integer}
 794      * object equal to the value of:
 795      *
 796      * <blockquote>
 797      *  {@code getInteger(nm, null)}
 798      * </blockquote>
 799      *
 800      * @param   nm   property name.
 801      * @return  the {@code Integer} value of the property.
 802      * @see     java.lang.System#getProperty(java.lang.String)
 803      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 804      */
 805     public static Integer getInteger(String nm) {
 806         return getInteger(nm, null);
 807     }
 808 
 809     /**
 810      * Determines the integer value of the system property with the
 811      * specified name.
 812      *
 813      * <p>The first argument is treated as the name of a system property.
 814      * System properties are accessible through the {@link
 815      * java.lang.System#getProperty(java.lang.String)} method. The
 816      * string value of this property is then interpreted as an integer
 817      * value and an {@code Integer} object representing this value is
 818      * returned. Details of possible numeric formats can be found with
 819      * the definition of {@code getProperty}.
 820      *
 821      * <p>The second argument is the default value. An {@code Integer} object
 822      * that represents the value of the second argument is returned if there
 823      * is no property of the specified name, if the property does not have
 824      * the correct numeric format, or if the specified name is empty or
 825      * {@code null}.
 826      *
 827      * <p>In other words, this method returns an {@code Integer} object
 828      * equal to the value of:
 829      *
 830      * <blockquote>
 831      *  {@code getInteger(nm, new Integer(val))}
 832      * </blockquote>
 833      *
 834      * but in practice it may be implemented in a manner such as:
 835      *
 836      * <blockquote><pre>
 837      * Integer result = getInteger(nm, null);
 838      * return (result == null) ? new Integer(val) : result;
 839      * </pre></blockquote>
 840      *
 841      * to avoid the unnecessary allocation of an {@code Integer}
 842      * object when the default value is not needed.
 843      *
 844      * @param   nm   property name.
 845      * @param   val   default value.
 846      * @return  the {@code Integer} value of the property.
 847      * @see     java.lang.System#getProperty(java.lang.String)
 848      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 849      */
 850     public static Integer getInteger(String nm, int val) {
 851         Integer result = getInteger(nm, null);
 852         return (result == null) ? Integer.valueOf(val) : result;
 853     }
 854 
 855     /**
 856      * Returns the integer value of the system property with the
 857      * specified name.  The first argument is treated as the name of a
 858      * system property.  System properties are accessible through the
 859      * {@link java.lang.System#getProperty(java.lang.String)} method.
 860      * The string value of this property is then interpreted as an
 861      * integer value, as per the {@code Integer.decode} method,
 862      * and an {@code Integer} object representing this value is
 863      * returned.
 864      *
 865      * <ul><li>If the property value begins with the two ASCII characters
 866      *         {@code 0x} or the ASCII character {@code #}, not
 867      *      followed by a minus sign, then the rest of it is parsed as a
 868      *      hexadecimal integer exactly as by the method
 869      *      {@link #valueOf(java.lang.String, int)} with radix 16.
 870      * <li>If the property value begins with the ASCII character
 871      *     {@code 0} followed by another character, it is parsed as an
 872      *     octal integer exactly as by the method
 873      *     {@link #valueOf(java.lang.String, int)} with radix 8.
 874      * <li>Otherwise, the property value is parsed as a decimal integer
 875      * exactly as by the method {@link #valueOf(java.lang.String, int)}
 876      * with radix 10.
 877      * </ul>
 878      *
 879      * <p>The second argument is the default value. The default value is
 880      * returned if there is no property of the specified name, if the
 881      * property does not have the correct numeric format, or if the
 882      * specified name is empty or {@code null}.
 883      *
 884      * @param   nm   property name.
 885      * @param   val   default value.
 886      * @return  the {@code Integer} value of the property.
 887      * @see     java.lang.System#getProperty(java.lang.String)
 888      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
 889      * @see java.lang.Integer#decode
 890      */
 891     public static Integer getInteger(String nm, Integer val) {
 892         String v = null;
 893         try {
 894             v = System.getProperty(nm);
 895         } catch (IllegalArgumentException e) {
 896         } catch (NullPointerException e) {
 897         }
 898         if (v != null) {
 899             try {
 900                 return Integer.decode(v);
 901             } catch (NumberFormatException e) {
 902             }
 903         }
 904         return val;
 905     }
 906 
 907     /**
 908      * Decodes a {@code String} into an {@code Integer}.
 909      * Accepts decimal, hexadecimal, and octal numbers given
 910      * by the following grammar:
 911      *
 912      * <blockquote>
 913      * <dl>
 914      * <dt><i>DecodableString:</i>
 915      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
 916      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
 917      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
 918      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
 919      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
 920      * <p>
 921      * <dt><i>Sign:</i>
 922      * <dd>{@code -}
 923      * <dd>{@code +}
 924      * </dl>
 925      * </blockquote>
 926      *
 927      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
 928      * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a>
 929      * of the <a href="http://java.sun.com/docs/books/jls/html/">Java
 930      * Language Specification</a>.
 931      *
 932      * <p>The sequence of characters following an optional
 933      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
 934      * "{@code #}", or leading zero) is parsed as by the {@code
 935      * Integer.parseInt} method with the indicated radix (10, 16, or
 936      * 8).  This sequence of characters must represent a positive
 937      * value or a {@link NumberFormatException} will be thrown.  The
 938      * result is negated if first character of the specified {@code
 939      * String} is the minus sign.  No whitespace characters are
 940      * permitted in the {@code String}.
 941      *
 942      * @param     nm the {@code String} to decode.
 943      * @return    an {@code Integer} object holding the {@code int}
 944      *             value represented by {@code nm}
 945      * @exception NumberFormatException  if the {@code String} does not
 946      *            contain a parsable integer.
 947      * @see java.lang.Integer#parseInt(java.lang.String, int)
 948      */
 949     public static Integer decode(String nm) throws NumberFormatException {
 950         int radix = 10;
 951         int index = 0;
 952         boolean negative = false;
 953         Integer result;
 954 
 955         if (nm.length() == 0)
 956             throw new NumberFormatException("Zero length string");
 957         char firstChar = nm.charAt(0);
 958         // Handle sign, if present
 959         if (firstChar == '-') {
 960             negative = true;
 961             index++;
 962         } else if (firstChar == '+')
 963             index++;
 964 
 965         // Handle radix specifier, if present
 966         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
 967             index += 2;
 968             radix = 16;
 969         }
 970         else if (nm.startsWith("#", index)) {
 971             index ++;
 972             radix = 16;
 973         }
 974         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
 975             index ++;
 976             radix = 8;
 977         }
 978 
 979         if (nm.startsWith("-", index) || nm.startsWith("+", index))
 980             throw new NumberFormatException("Sign character in wrong position");
 981 
 982         try {
 983             result = Integer.valueOf(nm.substring(index), radix);
 984             result = negative ? Integer.valueOf(-result.intValue()) : result;
 985         } catch (NumberFormatException e) {
 986             // If number is Integer.MIN_VALUE, we'll end up here. The next line
 987             // handles this case, and causes any genuine format error to be
 988             // rethrown.
 989             String constant = negative ? ("-" + nm.substring(index))
 990                                        : nm.substring(index);
 991             result = Integer.valueOf(constant, radix);
 992         }
 993         return result;
 994     }
 995 
 996     /**
 997      * Compares two {@code Integer} objects numerically.
 998      *
 999      * @param   anotherInteger   the {@code Integer} to be compared.
1000      * @return  the value {@code 0} if this {@code Integer} is
1001      *          equal to the argument {@code Integer}; a value less than
1002      *          {@code 0} if this {@code Integer} is numerically less
1003      *          than the argument {@code Integer}; and a value greater
1004      *          than {@code 0} if this {@code Integer} is numerically
1005      *           greater than the argument {@code Integer} (signed
1006      *           comparison).
1007      * @since   1.2
1008      */
1009     public int compareTo(Integer anotherInteger) {
1010         int thisVal = this.value;
1011         int anotherVal = anotherInteger.value;
1012         return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
1013     }
1014 
1015 
1016     // Bit twiddling
1017 
1018     /**
1019      * The number of bits used to represent an {@code int} value in two's
1020      * complement binary form.
1021      *
1022      * @since 1.5
1023      */
1024     public static final int SIZE = 32;
1025 
1026     /**
1027      * Returns an {@code int} value with at most a single one-bit, in the
1028      * position of the highest-order ("leftmost") one-bit in the specified
1029      * {@code int} value.  Returns zero if the specified value has no
1030      * one-bits in its two's complement binary representation, that is, if it
1031      * is equal to zero.
1032      *
1033      * @return an {@code int} value with a single one-bit, in the position
1034      *     of the highest-order one-bit in the specified value, or zero if
1035      *     the specified value is itself equal to zero.
1036      * @since 1.5
1037      */
1038     public static int highestOneBit(int i) {
1039         // HD, Figure 3-1
1040         i |= (i >>  1);
1041         i |= (i >>  2);
1042         i |= (i >>  4);
1043         i |= (i >>  8);
1044         i |= (i >> 16);
1045         return i - (i >>> 1);
1046     }
1047 
1048     /**
1049      * Returns an {@code int} value with at most a single one-bit, in the
1050      * position of the lowest-order ("rightmost") one-bit in the specified
1051      * {@code int} value.  Returns zero if the specified value has no
1052      * one-bits in its two's complement binary representation, that is, if it
1053      * is equal to zero.
1054      *
1055      * @return an {@code int} value with a single one-bit, in the position
1056      *     of the lowest-order one-bit in the specified value, or zero if
1057      *     the specified value is itself equal to zero.
1058      * @since 1.5
1059      */
1060     public static int lowestOneBit(int i) {
1061         // HD, Section 2-1
1062         return i & -i;
1063     }
1064 
1065     /**
1066      * Returns the number of zero bits preceding the highest-order
1067      * ("leftmost") one-bit in the two's complement binary representation
1068      * of the specified {@code int} value.  Returns 32 if the
1069      * specified value has no one-bits in its two's complement representation,
1070      * in other words if it is equal to zero.
1071      *
1072      * <p>Note that this method is closely related to the logarithm base 2.
1073      * For all positive {@code int} values x:
1074      * <ul>
1075      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1076      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1077      * </ul>
1078      *
1079      * @return the number of zero bits preceding the highest-order
1080      *     ("leftmost") one-bit in the two's complement binary representation
1081      *     of the specified {@code int} value, or 32 if the value
1082      *     is equal to zero.
1083      * @since 1.5
1084      */
1085     public static int numberOfLeadingZeros(int i) {
1086         // HD, Figure 5-6
1087         if (i == 0)
1088             return 32;
1089         int n = 1;
1090         if (i >>> 16 == 0) { n += 16; i <<= 16; }
1091         if (i >>> 24 == 0) { n +=  8; i <<=  8; }
1092         if (i >>> 28 == 0) { n +=  4; i <<=  4; }
1093         if (i >>> 30 == 0) { n +=  2; i <<=  2; }
1094         n -= i >>> 31;
1095         return n;
1096     }
1097 
1098     /**
1099      * Returns the number of zero bits following the lowest-order ("rightmost")
1100      * one-bit in the two's complement binary representation of the specified
1101      * {@code int} value.  Returns 32 if the specified value has no
1102      * one-bits in its two's complement representation, in other words if it is
1103      * equal to zero.
1104      *
1105      * @return the number of zero bits following the lowest-order ("rightmost")
1106      *     one-bit in the two's complement binary representation of the
1107      *     specified {@code int} value, or 32 if the value is equal
1108      *     to zero.
1109      * @since 1.5
1110      */
1111     public static int numberOfTrailingZeros(int i) {
1112         // HD, Figure 5-14
1113         int y;
1114         if (i == 0) return 32;
1115         int n = 31;
1116         y = i <<16; if (y != 0) { n = n -16; i = y; }
1117         y = i << 8; if (y != 0) { n = n - 8; i = y; }
1118         y = i << 4; if (y != 0) { n = n - 4; i = y; }
1119         y = i << 2; if (y != 0) { n = n - 2; i = y; }
1120         return n - ((i << 1) >>> 31);
1121     }
1122 
1123     /**
1124      * Returns the number of one-bits in the two's complement binary
1125      * representation of the specified {@code int} value.  This function is
1126      * sometimes referred to as the <i>population count</i>.
1127      *
1128      * @return the number of one-bits in the two's complement binary
1129      *     representation of the specified {@code int} value.
1130      * @since 1.5
1131      */
1132     public static int bitCount(int i) {
1133         // HD, Figure 5-2
1134         i = i - ((i >>> 1) & 0x55555555);
1135         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1136         i = (i + (i >>> 4)) & 0x0f0f0f0f;
1137         i = i + (i >>> 8);
1138         i = i + (i >>> 16);
1139         return i & 0x3f;
1140     }
1141 
1142     /**
1143      * Returns the value obtained by rotating the two's complement binary
1144      * representation of the specified {@code int} value left by the
1145      * specified number of bits.  (Bits shifted out of the left hand, or
1146      * high-order, side reenter on the right, or low-order.)
1147      *
1148      * <p>Note that left rotation with a negative distance is equivalent to
1149      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1150      * distance)}.  Note also that rotation by any multiple of 32 is a
1151      * no-op, so all but the last five bits of the rotation distance can be
1152      * ignored, even if the distance is negative: {@code rotateLeft(val,
1153      * distance) == rotateLeft(val, distance & 0x1F)}.
1154      *
1155      * @return the value obtained by rotating the two's complement binary
1156      *     representation of the specified {@code int} value left by the
1157      *     specified number of bits.
1158      * @since 1.5
1159      */
1160     public static int rotateLeft(int i, int distance) {
1161         return (i << distance) | (i >>> -distance);
1162     }
1163 
1164     /**
1165      * Returns the value obtained by rotating the two's complement binary
1166      * representation of the specified {@code int} value right by the
1167      * specified number of bits.  (Bits shifted out of the right hand, or
1168      * low-order, side reenter on the left, or high-order.)
1169      *
1170      * <p>Note that right rotation with a negative distance is equivalent to
1171      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1172      * distance)}.  Note also that rotation by any multiple of 32 is a
1173      * no-op, so all but the last five bits of the rotation distance can be
1174      * ignored, even if the distance is negative: {@code rotateRight(val,
1175      * distance) == rotateRight(val, distance & 0x1F)}.
1176      *
1177      * @return the value obtained by rotating the two's complement binary
1178      *     representation of the specified {@code int} value right by the
1179      *     specified number of bits.
1180      * @since 1.5
1181      */
1182     public static int rotateRight(int i, int distance) {
1183         return (i >>> distance) | (i << -distance);
1184     }
1185 
1186     /**
1187      * Returns the value obtained by reversing the order of the bits in the
1188      * two's complement binary representation of the specified {@code int}
1189      * value.
1190      *
1191      * @return the value obtained by reversing order of the bits in the
1192      *     specified {@code int} value.
1193      * @since 1.5
1194      */
1195     public static int reverse(int i) {
1196         // HD, Figure 7-1
1197         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1198         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1199         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1200         i = (i << 24) | ((i & 0xff00) << 8) |
1201             ((i >>> 8) & 0xff00) | (i >>> 24);
1202         return i;
1203     }
1204 
1205     /**
1206      * Returns the signum function of the specified {@code int} value.  (The
1207      * return value is -1 if the specified value is negative; 0 if the
1208      * specified value is zero; and 1 if the specified value is positive.)
1209      *
1210      * @return the signum function of the specified {@code int} value.
1211      * @since 1.5
1212      */
1213     public static int signum(int i) {
1214         // HD, Section 2-7
1215         return (i >> 31) | (-i >>> 31);
1216     }
1217 
1218     /**
1219      * Returns the value obtained by reversing the order of the bytes in the
1220      * two's complement representation of the specified {@code int} value.
1221      *
1222      * @return the value obtained by reversing the bytes in the specified
1223      *     {@code int} value.
1224      * @since 1.5
1225      */
1226     public static int reverseBytes(int i) {
1227         return ((i >>> 24)           ) |
1228                ((i >>   8) &   0xFF00) |
1229                ((i <<   8) & 0xFF0000) |
1230                ((i << 24));
1231     }
1232 
1233     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1234     private static final long serialVersionUID = 1360826667806852920L;
1235 }