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 /**
  29  * The {@code Integer} class wraps a value of the primitive type
  30  * {@code int} in an object. An object of type {@code Integer}
  31  * contains a single field whose type is {@code int}.
  32  *
  33  * <p>In addition, this class provides several methods for converting
  34  * an {@code int} to a {@code String} and a {@code String} to an
  35  * {@code int}, as well as other constants and methods useful when
  36  * dealing with an {@code int}.
  37  *
  38  * <p>Implementation note: The implementations of the "bit twiddling"
  39  * methods (such as {@link #highestOneBit(int) highestOneBit} and
  40  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
  41  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  42  * Delight</i>, (Addison Wesley, 2002).
  43  *
  44  * @author  Lee Boynton
  45  * @author  Arthur van Hoff
  46  * @author  Josh Bloch
  47  * @author  Joseph D. Darcy
  48  * @since JDK1.0
  49  */
  50 public final class Integer extends Number implements Comparable<Integer> {
  51     /**
  52      * A constant holding the minimum value an {@code int} can
  53      * have, -2<sup>31</sup>.
  54      */
  55     public static final int   MIN_VALUE = 0x80000000;
  56 
  57     /**
  58      * A constant holding the maximum value an {@code int} can
  59      * have, 2<sup>31</sup>-1.
  60      */
  61     public static final int   MAX_VALUE = 0x7fffffff;
  62 
  63     /**
  64      * The {@code Class} instance representing the primitive type
  65      * {@code int}.
  66      *
  67      * @since   JDK1.1
  68      */
  69     public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
  70 
  71     /**
  72      * All possible chars for representing a number as a String
  73      */
  74     final static char[] digits = {
  75         '0' , '1' , '2' , '3' , '4' , '5' ,
  76         '6' , '7' , '8' , '9' , 'a' , 'b' ,
  77         'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
  78         'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
  79         'o' , 'p' , 'q' , 'r' , 's' , 't' ,
  80         'u' , 'v' , 'w' , 'x' , 'y' , 'z'
  81     };
  82 
  83     /**
  84      * Returns a string representation of the first argument in the
  85      * radix specified by the second argument.
  86      *
  87      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
  88      * or larger than {@code Character.MAX_RADIX}, then the radix
  89      * {@code 10} is used instead.
  90      *
  91      * <p>If the first argument is negative, the first element of the
  92      * result is the ASCII minus character {@code '-'}
  93      * (<code>'&#92;u002D'</code>). If the first argument is not
  94      * negative, no sign character appears in the result.
  95      *
  96      * <p>The remaining characters of the result represent the magnitude
  97      * of the first argument. If the magnitude is zero, it is
  98      * represented by a single zero character {@code '0'}
  99      * (<code>'&#92;u0030'</code>); otherwise, the first character of
 100      * the representation of the magnitude will not be the zero
 101      * character.  The following ASCII characters are used as digits:
 102      *
 103      * <blockquote>
 104      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
 105      * </blockquote>
 106      *
 107      * These are <code>'&#92;u0030'</code> through
 108      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
 109      * <code>'&#92;u007A'</code>. If {@code radix} is
 110      * <var>N</var>, then the first <var>N</var> of these characters
 111      * are used as radix-<var>N</var> digits in the order shown. Thus,
 112      * the digits for hexadecimal (radix 16) are
 113      * {@code 0123456789abcdef}. If uppercase letters are
 114      * desired, the {@link java.lang.String#toUpperCase()} method may
 115      * be called on the result:
 116      *
 117      * <blockquote>
 118      *  {@code Integer.toString(n, 16).toUpperCase()}
 119      * </blockquote>
 120      *
 121      * @param   i       an integer to be converted to a string.
 122      * @param   radix   the radix to use in the string representation.
 123      * @return  a string representation of the argument in the specified radix.
 124      * @see     java.lang.Character#MAX_RADIX
 125      * @see     java.lang.Character#MIN_RADIX
 126      */
 127     public static String toString(int i, int radix) {
 128 
 129         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 130             radix = 10;
 131 
 132         /* Use the faster version */
 133         if (radix == 10) {
 134             return toString(i);
 135         }
 136 
 137         char buf[] = new char[33];
 138         boolean negative = (i < 0);
 139         int charPos = 32;
 140 
 141         if (!negative) {
 142             i = -i;
 143         }
 144 
 145         while (i <= -radix) {
 146             buf[charPos--] = digits[-(i % radix)];
 147             i = i / radix;
 148         }
 149         buf[charPos] = digits[-i];
 150 
 151         if (negative) {
 152             buf[--charPos] = '-';
 153         }
 154 
 155         return new String(buf, charPos, (33 - charPos));
 156     }
 157 
 158     /**
 159      * Returns a string representation of the integer argument as an
 160      * unsigned integer in base&nbsp;16.
 161      *
 162      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 163      * if the argument is negative; otherwise, it is equal to the
 164      * argument.  This value is converted to a string of ASCII digits
 165      * in hexadecimal (base&nbsp;16) with no extra leading
 166      * {@code 0}s. If the unsigned magnitude is zero, it is
 167      * represented by a single zero character {@code '0'}
 168      * (<code>'&#92;u0030'</code>); otherwise, the first character of
 169      * the representation of the unsigned magnitude will not be the
 170      * zero character. The following characters are used as
 171      * hexadecimal digits:
 172      *
 173      * <blockquote>
 174      *  {@code 0123456789abcdef}
 175      * </blockquote>
 176      *
 177      * These are the characters <code>'&#92;u0030'</code> through
 178      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
 179      * <code>'&#92;u0066'</code>. If uppercase letters are
 180      * desired, the {@link java.lang.String#toUpperCase()} method may
 181      * be called on the result:
 182      *
 183      * <blockquote>
 184      *  {@code Integer.toHexString(n).toUpperCase()}
 185      * </blockquote>
 186      *
 187      * @param   i   an integer to be converted to a string.
 188      * @return  the string representation of the unsigned integer value
 189      *          represented by the argument in hexadecimal (base&nbsp;16).
 190      * @since   JDK1.0.2
 191      */
 192     public static String toHexString(int i) {
 193         return toUnsignedString(i, 4);
 194     }
 195 
 196     /**
 197      * Returns a string representation of the integer argument as an
 198      * unsigned integer in base&nbsp;8.
 199      *
 200      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 201      * if the argument is negative; otherwise, it is equal to the
 202      * argument.  This value is converted to a string of ASCII digits
 203      * in octal (base&nbsp;8) with no extra leading {@code 0}s.
 204      *
 205      * <p>If the unsigned magnitude is zero, it is represented by a
 206      * single zero character {@code '0'}
 207      * (<code>'&#92;u0030'</code>); otherwise, the first character of
 208      * the representation of the unsigned magnitude will not be the
 209      * zero character. The following characters are used as octal
 210      * digits:
 211      *
 212      * <blockquote>
 213      * {@code 01234567}
 214      * </blockquote>
 215      *
 216      * These are the characters <code>'&#92;u0030'</code> through
 217      * <code>'&#92;u0037'</code>.
 218      *
 219      * @param   i   an integer to be converted to a string.
 220      * @return  the string representation of the unsigned integer value
 221      *          represented by the argument in octal (base&nbsp;8).
 222      * @since   JDK1.0.2
 223      */
 224     public static String toOctalString(int i) {
 225         return toUnsignedString(i, 3);
 226     }
 227 
 228     /**
 229      * Returns a string representation of the integer argument as an
 230      * unsigned integer in base&nbsp;2.
 231      *
 232      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 233      * if the argument is negative; otherwise it is equal to the
 234      * argument.  This value is converted to a string of ASCII digits
 235      * in binary (base&nbsp;2) with no extra leading {@code 0}s.
 236      * If the unsigned magnitude is zero, it is represented by a
 237      * single zero character {@code '0'}
 238      * (<code>'&#92;u0030'</code>); otherwise, the first character of
 239      * the representation of the unsigned magnitude will not be the
 240      * zero character. The characters {@code '0'}
 241      * (<code>'&#92;u0030'</code>) and {@code '1'}
 242      * (<code>'&#92;u0031'</code>) are used as binary digits.
 243      *
 244      * @param   i   an integer to be converted to a string.
 245      * @return  the string representation of the unsigned integer value
 246      *          represented by the argument in binary (base&nbsp;2).
 247      * @since   JDK1.0.2
 248      */
 249     public static String toBinaryString(int i) {
 250         return toUnsignedString(i, 1);
 251     }
 252 
 253     /**
 254      * Convert the integer to an unsigned number.
 255      */
 256     private static String toUnsignedString(int i, int shift) {
 257         char[] buf = new char[32];
 258         int charPos = 32;
 259         int radix = 1 << shift;
 260         int mask = radix - 1;
 261         do {
 262             buf[--charPos] = digits[i & mask];
 263             i >>>= shift;
 264         } while (i != 0);
 265 
 266         return new String(buf, charPos, (32 - charPos));
 267     }
 268 
 269 
 270     final static char [] DigitTens = {
 271         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
 272         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
 273         '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
 274         '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
 275         '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
 276         '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
 277         '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
 278         '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
 279         '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
 280         '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
 281         } ;
 282 
 283     final static char [] DigitOnes = {
 284         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 285         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 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         } ;
 295 
 296         // I use the "invariant division by multiplication" trick to
 297         // accelerate Integer.toString.  In particular we want to
 298         // avoid division by 10.
 299         //
 300         // The "trick" has roughly the same performance characteristics
 301         // as the "classic" Integer.toString code on a non-JIT VM.
 302         // The trick avoids .rem and .div calls but has a longer code
 303         // path and is thus dominated by dispatch overhead.  In the
 304         // JIT case the dispatch overhead doesn't exist and the
 305         // "trick" is considerably faster than the classic code.
 306         //
 307         // TODO-FIXME: convert (x * 52429) into the equiv shift-add
 308         // sequence.
 309         //
 310         // RE:  Division by Invariant Integers using Multiplication
 311         //      T Gralund, P Montgomery
 312         //      ACM PLDI 1994
 313         //
 314 
 315     /**
 316      * Returns a {@code String} object representing the
 317      * specified integer. The argument is converted to signed decimal
 318      * representation and returned as a string, exactly as if the
 319      * argument and radix 10 were given as arguments to the {@link
 320      * #toString(int, int)} method.
 321      *
 322      * @param   i   an integer to be converted.
 323      * @return  a string representation of the argument in base&nbsp;10.
 324      */
 325     public static String toString(int i) {
 326         if (i == Integer.MIN_VALUE)
 327             return "-2147483648";
 328         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
 329         char[] buf = new char[size];
 330         getChars(i, size, buf);
 331         return new String(0, size, buf);
 332     }
 333 
 334     /**
 335      * Places characters representing the integer i into the
 336      * character array buf. The characters are placed into
 337      * the buffer backwards starting with the least significant
 338      * digit at the specified index (exclusive), and working
 339      * backwards from there.
 340      *
 341      * Will fail if i == Integer.MIN_VALUE
 342      */
 343     static void getChars(int i, int index, char[] buf) {
 344         int q, r;
 345         int charPos = index;
 346         char sign = 0;
 347 
 348         if (i < 0) {
 349             sign = '-';
 350             i = -i;
 351         }
 352 
 353         // Generate two digits per iteration
 354         while (i >= 65536) {
 355             q = i / 100;
 356         // really: r = i - (q * 100);
 357             r = i - ((q << 6) + (q << 5) + (q << 2));
 358             i = q;
 359             buf [--charPos] = DigitOnes[r];
 360             buf [--charPos] = DigitTens[r];
 361         }
 362 
 363         // Fall thru to fast mode for smaller numbers
 364         // assert(i <= 65536, i);
 365         for (;;) {
 366             q = (i * 52429) >>> (16+3);
 367             r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
 368             buf [--charPos] = digits [r];
 369             i = q;
 370             if (i == 0) break;
 371         }
 372         if (sign != 0) {
 373             buf [--charPos] = sign;
 374         }
 375     }
 376 
 377     final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
 378                                       99999999, 999999999, Integer.MAX_VALUE };
 379 
 380     // Requires positive x
 381     static int stringSize(int x) {
 382         for (int i=0; ; i++)
 383             if (x <= sizeTable[i])
 384                 return i+1;
 385     }
 386 
 387     /**
 388      * Parses the string argument as a signed integer in the radix
 389      * specified by the second argument. The characters in the string
 390      * must all be digits of the specified radix (as determined by
 391      * whether {@link java.lang.Character#digit(char, int)} returns a
 392      * nonnegative value), except that the first character may be an
 393      * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
 394      * indicate a negative value or an ASCII plus sign {@code '+'}
 395      * (<code>'&#92;u002B'</code>) to indicate a positive value. The
 396      * resulting integer value is returned.
 397      *
 398      * <p>An exception of type {@code NumberFormatException} is
 399      * thrown if any of the following situations occurs:
 400      * <ul>
 401      * <li>The first argument is {@code null} or is a string of
 402      * length zero.
 403      *
 404      * <li>The radix is either smaller than
 405      * {@link java.lang.Character#MIN_RADIX} or
 406      * larger than {@link java.lang.Character#MAX_RADIX}.
 407      *
 408      * <li>Any character of the string is not a digit of the specified
 409      * radix, except that the first character may be a minus sign
 410      * {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
 411      * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
 412      * string is longer than length 1.
 413      *
 414      * <li>The value represented by the string is not a value of type
 415      * {@code int}.
 416      * </ul>
 417      *
 418      * <p>Examples:
 419      * <blockquote><pre>
 420      * parseInt("0", 10) returns 0
 421      * parseInt("473", 10) returns 473
 422      * parseInt("+42", 10) returns 42
 423      * parseInt("-0", 10) returns 0
 424      * parseInt("-FF", 16) returns -255
 425      * parseInt("1100110", 2) returns 102
 426      * parseInt("2147483647", 10) returns 2147483647
 427      * parseInt("-2147483648", 10) returns -2147483648
 428      * parseInt("2147483648", 10) throws a NumberFormatException
 429      * parseInt("99", 8) throws a NumberFormatException
 430      * parseInt("Kona", 10) throws a NumberFormatException
 431      * parseInt("Kona", 27) returns 411787
 432      * </pre></blockquote>
 433      *
 434      * @param      s   the {@code String} containing the integer
 435      *                  representation to be parsed
 436      * @param      radix   the radix to be used while parsing {@code s}.
 437      * @return     the integer represented by the string argument in the
 438      *             specified radix.
 439      * @exception  NumberFormatException if the {@code String}
 440      *             does not contain a parsable {@code int}.
 441      */
 442     public static int parseInt(String s, int radix)
 443                 throws NumberFormatException
 444     {
 445         if (s == null) {
 446             throw new NumberFormatException("null");
 447         }
 448 
 449         if (radix < Character.MIN_RADIX) {
 450             throw new NumberFormatException("radix " + radix +
 451                                             " less than Character.MIN_RADIX");
 452         }
 453 
 454         if (radix > Character.MAX_RADIX) {
 455             throw new NumberFormatException("radix " + radix +
 456                                             " greater than Character.MAX_RADIX");
 457         }
 458 
 459         int result = 0;
 460         boolean negative = false;
 461         int i = 0, len = s.length();
 462         int limit = -Integer.MAX_VALUE;
 463         int multmin;
 464         int digit;
 465 
 466         if (len > 0) {
 467             char firstChar = s.charAt(0);
 468             if (firstChar < '0') { // Possible leading "+" or "-"
 469                 if (firstChar == '-') {
 470                     negative = true;
 471                     limit = Integer.MIN_VALUE;
 472                 } else if (firstChar != '+')
 473                     throw NumberFormatException.forInputString(s);
 474 
 475                 if (len == 1) // Cannot have lone "+" or "-"
 476                     throw NumberFormatException.forInputString(s);
 477                 i++;
 478             }
 479             multmin = limit / radix;
 480             while (i < len) {
 481                 // Accumulating negatively avoids surprises near MAX_VALUE
 482                 digit = Character.digit(s.charAt(i++),radix);
 483                 if (digit < 0) {
 484                     throw NumberFormatException.forInputString(s);
 485                 }
 486                 if (result < multmin) {
 487                     throw NumberFormatException.forInputString(s);
 488                 }
 489                 result *= radix;
 490                 if (result < limit + digit) {
 491                     throw NumberFormatException.forInputString(s);
 492                 }
 493                 result -= digit;
 494             }
 495         } else {
 496             throw NumberFormatException.forInputString(s);
 497         }
 498         return negative ? result : -result;
 499     }
 500 
 501     /**
 502      * Parses the string argument as a signed decimal integer. The
 503      * characters in the string must all be decimal digits, except
 504      * that the first character may be an ASCII minus sign {@code '-'}
 505      * (<code>'&#92;u002D'</code>) to indicate a negative value or an
 506      * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
 507      * indicate a positive value. The resulting integer value is
 508      * returned, exactly as if the argument and the radix 10 were
 509      * given as arguments to the {@link #parseInt(java.lang.String,
 510      * int)} method.
 511      *
 512      * @param s    a {@code String} containing the {@code int}
 513      *             representation to be parsed
 514      * @return     the integer value represented by the argument in decimal.
 515      * @exception  NumberFormatException  if the string does not contain a
 516      *               parsable integer.
 517      */
 518     public static int parseInt(String s) throws NumberFormatException {
 519         return parseInt(s,10);
 520     }
 521 
 522     /**
 523      * Returns an {@code Integer} object holding the value
 524      * extracted from the specified {@code String} when parsed
 525      * with the radix given by the second argument. The first argument
 526      * is interpreted as representing a signed integer in the radix
 527      * specified by the second argument, exactly as if the arguments
 528      * were given to the {@link #parseInt(java.lang.String, int)}
 529      * method. The result is an {@code Integer} object that
 530      * represents the integer value specified by the string.
 531      *
 532      * <p>In other words, this method returns an {@code Integer}
 533      * object equal to the value of:
 534      *
 535      * <blockquote>
 536      *  {@code new Integer(Integer.parseInt(s, radix))}
 537      * </blockquote>
 538      *
 539      * @param      s   the string to be parsed.
 540      * @param      radix the radix to be used in interpreting {@code s}
 541      * @return     an {@code Integer} object holding the value
 542      *             represented by the string argument in the specified
 543      *             radix.
 544      * @exception NumberFormatException if the {@code String}
 545      *            does not contain a parsable {@code int}.
 546      */
 547     public static Integer valueOf(String s, int radix) throws NumberFormatException {
 548         return new Integer(parseInt(s,radix));
 549     }
 550 
 551     /**
 552      * Returns an {@code Integer} object holding the
 553      * value of the specified {@code String}. The argument is
 554      * interpreted as representing a signed decimal integer, exactly
 555      * as if the argument were given to the {@link
 556      * #parseInt(java.lang.String)} method. The result is an
 557      * {@code Integer} object that represents the integer value
 558      * specified by the string.
 559      *
 560      * <p>In other words, this method returns an {@code Integer}
 561      * object equal to the value of:
 562      *
 563      * <blockquote>
 564      *  {@code new Integer(Integer.parseInt(s))}
 565      * </blockquote>
 566      *
 567      * @param      s   the string to be parsed.
 568      * @return     an {@code Integer} object holding the value
 569      *             represented by the string argument.
 570      * @exception  NumberFormatException  if the string cannot be parsed
 571      *             as an integer.
 572      */
 573     public static Integer valueOf(String s) throws NumberFormatException
 574     {
 575         return new Integer(parseInt(s, 10));
 576     }
 577 
 578     private static class IntegerCache {
 579         private IntegerCache(){}
 580 
 581         static final Integer cache[] = new Integer[-(-128) + 127 + 1];
 582 
 583         static {
 584             for(int i = 0; i < cache.length; i++)
 585                 cache[i] = new Integer(i - 128);
 586         }
 587     }
 588 
 589     /**
 590      * Returns an {@code Integer} instance representing the specified
 591      * {@code int} value.  If a new {@code Integer} instance is not
 592      * required, this method should generally be used in preference to
 593      * the constructor {@link #Integer(int)}, as this method is likely
 594      * to yield significantly better space and time performance by
 595      * caching frequently requested values.
 596      *
 597      * @param  i an {@code int} value.
 598      * @return an {@code Integer} instance representing {@code i}.
 599      * @since  1.5
 600      */
 601     public static Integer valueOf(int i) {
 602         final int offset = 128;
 603         if (i >= -128 && i <= 127) { // must cache
 604             return IntegerCache.cache[i + offset];
 605         }
 606         return new Integer(i);
 607     }
 608 
 609     /**
 610      * The value of the {@code Integer}.
 611      *
 612      * @serial
 613      */
 614     private final int value;
 615 
 616     /**
 617      * Constructs a newly allocated {@code Integer} object that
 618      * represents the specified {@code int} value.
 619      *
 620      * @param   value   the value to be represented by the
 621      *                  {@code Integer} object.
 622      */
 623     public Integer(int value) {
 624         this.value = value;
 625     }
 626 
 627     /**
 628      * Constructs a newly allocated {@code Integer} object that
 629      * represents the {@code int} value indicated by the
 630      * {@code String} parameter. The string is converted to an
 631      * {@code int} value in exactly the manner used by the
 632      * {@code parseInt} method for radix 10.
 633      *
 634      * @param      s   the {@code String} to be converted to an
 635      *                 {@code Integer}.
 636      * @exception  NumberFormatException  if the {@code String} does not
 637      *               contain a parsable integer.
 638      * @see        java.lang.Integer#parseInt(java.lang.String, int)
 639      */
 640     public Integer(String s) throws NumberFormatException {
 641         this.value = parseInt(s, 10);
 642     }
 643 
 644     /**
 645      * Returns the value of this {@code Integer} as a
 646      * {@code byte}.
 647      */
 648     public byte byteValue() {
 649         return (byte)value;
 650     }
 651 
 652     /**
 653      * Returns the value of this {@code Integer} as a
 654      * {@code short}.
 655      */
 656     public short shortValue() {
 657         return (short)value;
 658     }
 659 
 660     /**
 661      * Returns the value of this {@code Integer} as an
 662      * {@code int}.
 663      */
 664     public int intValue() {
 665         return value;
 666     }
 667 
 668     /**
 669      * Returns the value of this {@code Integer} as a
 670      * {@code long}.
 671      */
 672     public long longValue() {
 673         return (long)value;
 674     }
 675 
 676     /**
 677      * Returns the value of this {@code Integer} as a
 678      * {@code float}.
 679      */
 680     public float floatValue() {
 681         return (float)value;
 682     }
 683 
 684     /**
 685      * Returns the value of this {@code Integer} as a
 686      * {@code double}.
 687      */
 688     public double doubleValue() {
 689         return (double)value;
 690     }
 691 
 692     /**
 693      * Returns a {@code String} object representing this
 694      * {@code Integer}'s value. The value is converted to signed
 695      * decimal representation and returned as a string, exactly as if
 696      * the integer value were given as an argument to the {@link
 697      * java.lang.Integer#toString(int)} method.
 698      *
 699      * @return  a string representation of the value of this object in
 700      *          base&nbsp;10.
 701      */
 702     public String toString() {
 703         return String.valueOf(value);
 704     }
 705 
 706     /**
 707      * Returns a hash code for this {@code Integer}.
 708      *
 709      * @return  a hash code value for this object, equal to the
 710      *          primitive {@code int} value represented by this
 711      *          {@code Integer} object.
 712      */
 713     public int hashCode() {
 714         return value;
 715     }
 716 
 717     /**
 718      * Compares this object to the specified object.  The result is
 719      * {@code true} if and only if the argument is not
 720      * {@code null} and is an {@code Integer} object that
 721      * contains the same {@code int} value as this object.
 722      *
 723      * @param   obj   the object to compare with.
 724      * @return  {@code true} if the objects are the same;
 725      *          {@code false} otherwise.
 726      */
 727     public boolean equals(Object obj) {
 728         if (obj instanceof Integer) {
 729             return value == ((Integer)obj).intValue();
 730         }
 731         return false;
 732     }
 733 
 734     /**
 735      * Determines the integer value of the system property with the
 736      * specified name.
 737      *
 738      * <p>The first argument is treated as the name of a system property.
 739      * System properties are accessible through the
 740      * {@link java.lang.System#getProperty(java.lang.String)} method. The
 741      * string value of this property is then interpreted as an integer
 742      * value and an {@code Integer} object representing this value is
 743      * returned. Details of possible numeric formats can be found with
 744      * the definition of {@code getProperty}.
 745      *
 746      * <p>If there is no property with the specified name, if the specified name
 747      * is empty or {@code null}, or if the property does not have
 748      * the correct numeric format, then {@code null} is returned.
 749      *
 750      * <p>In other words, this method returns an {@code Integer}
 751      * object equal to the value of:
 752      *
 753      * <blockquote>
 754      *  {@code getInteger(nm, null)}
 755      * </blockquote>
 756      *
 757      * @param   nm   property name.
 758      * @return  the {@code Integer} value of the property.
 759      * @see     java.lang.System#getProperty(java.lang.String)
 760      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 761      */
 762     public static Integer getInteger(String nm) {
 763         return getInteger(nm, null);
 764     }
 765 
 766     /**
 767      * Determines the integer value of the system property with the
 768      * specified name.
 769      *
 770      * <p>The first argument is treated as the name of a system property.
 771      * System properties are accessible through the {@link
 772      * java.lang.System#getProperty(java.lang.String)} method. The
 773      * string value of this property is then interpreted as an integer
 774      * value and an {@code Integer} object representing this value is
 775      * returned. Details of possible numeric formats can be found with
 776      * the definition of {@code getProperty}.
 777      *
 778      * <p>The second argument is the default value. An {@code Integer} object
 779      * that represents the value of the second argument is returned if there
 780      * is no property of the specified name, if the property does not have
 781      * the correct numeric format, or if the specified name is empty or
 782      * {@code null}.
 783      *
 784      * <p>In other words, this method returns an {@code Integer} object
 785      * equal to the value of:
 786      *
 787      * <blockquote>
 788      *  {@code getInteger(nm, new Integer(val))}
 789      * </blockquote>
 790      *
 791      * but in practice it may be implemented in a manner such as:
 792      *
 793      * <blockquote><pre>
 794      * Integer result = getInteger(nm, null);
 795      * return (result == null) ? new Integer(val) : result;
 796      * </pre></blockquote>
 797      *
 798      * to avoid the unnecessary allocation of an {@code Integer}
 799      * object when the default value is not needed.
 800      *
 801      * @param   nm   property name.
 802      * @param   val   default value.
 803      * @return  the {@code Integer} value of the property.
 804      * @see     java.lang.System#getProperty(java.lang.String)
 805      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 806      */
 807     public static Integer getInteger(String nm, int val) {
 808         Integer result = getInteger(nm, null);
 809         return (result == null) ? new Integer(val) : result;
 810     }
 811 
 812     /**
 813      * Returns the integer value of the system property with the
 814      * specified name.  The first argument is treated as the name of a
 815      * system property.  System properties are accessible through the
 816      * {@link java.lang.System#getProperty(java.lang.String)} method.
 817      * The string value of this property is then interpreted as an
 818      * integer value, as per the {@code Integer.decode} method,
 819      * and an {@code Integer} object representing this value is
 820      * returned.
 821      *
 822      * <ul><li>If the property value begins with the two ASCII characters
 823      *         {@code 0x} or the ASCII character {@code #}, not
 824      *      followed by a minus sign, then the rest of it is parsed as a
 825      *      hexadecimal integer exactly as by the method
 826      *      {@link #valueOf(java.lang.String, int)} with radix 16.
 827      * <li>If the property value begins with the ASCII character
 828      *     {@code 0} followed by another character, it is parsed as an
 829      *     octal integer exactly as by the method
 830      *     {@link #valueOf(java.lang.String, int)} with radix 8.
 831      * <li>Otherwise, the property value is parsed as a decimal integer
 832      * exactly as by the method {@link #valueOf(java.lang.String, int)}
 833      * with radix 10.
 834      * </ul>
 835      *
 836      * <p>The second argument is the default value. The default value is
 837      * returned if there is no property of the specified name, if the
 838      * property does not have the correct numeric format, or if the
 839      * specified name is empty or {@code null}.
 840      *
 841      * @param   nm   property name.
 842      * @param   val   default value.
 843      * @return  the {@code Integer} value of the property.
 844      * @see     java.lang.System#getProperty(java.lang.String)
 845      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
 846      * @see java.lang.Integer#decode
 847      */
 848     public static Integer getInteger(String nm, Integer val) {
 849         String v = null;
 850         try {
 851             v = System.getProperty(nm);
 852         } catch (IllegalArgumentException e) {
 853         } catch (NullPointerException e) {
 854         }
 855         if (v != null) {
 856             try {
 857                 return Integer.decode(v);
 858             } catch (NumberFormatException e) {
 859             }
 860         }
 861         return val;
 862     }
 863 
 864     /**
 865      * Decodes a {@code String} into an {@code Integer}.
 866      * Accepts decimal, hexadecimal, and octal numbers given
 867      * by the following grammar:
 868      *
 869      * <blockquote>
 870      * <dl>
 871      * <dt><i>DecodableString:</i>
 872      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
 873      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
 874      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
 875      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
 876      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
 877      * <p>
 878      * <dt><i>Sign:</i>
 879      * <dd>{@code -}
 880      * <dd>{@code +}
 881      * </dl>
 882      * </blockquote>
 883      *
 884      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
 885      * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a>
 886      * of the <a href="http://java.sun.com/docs/books/jls/html/">Java
 887      * Language Specification</a>.
 888      *
 889      * <p>The sequence of characters following an optional
 890      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
 891      * "{@code #}", or leading zero) is parsed as by the {@code
 892      * Integer.parseInt} method with the indicated radix (10, 16, or
 893      * 8).  This sequence of characters must represent a positive
 894      * value or a {@link NumberFormatException} will be thrown.  The
 895      * result is negated if first character of the specified {@code
 896      * String} is the minus sign.  No whitespace characters are
 897      * permitted in the {@code String}.
 898      *
 899      * @param     nm the {@code String} to decode.
 900      * @return    an {@code Integer} object holding the {@code int}
 901      *             value represented by {@code nm}
 902      * @exception NumberFormatException  if the {@code String} does not
 903      *            contain a parsable integer.
 904      * @see java.lang.Integer#parseInt(java.lang.String, int)
 905      */
 906     public static Integer decode(String nm) throws NumberFormatException {
 907         int radix = 10;
 908         int index = 0;
 909         boolean negative = false;
 910         Integer result;
 911 
 912         if (nm.length() == 0)
 913             throw new NumberFormatException("Zero length string");
 914         char firstChar = nm.charAt(0);
 915         // Handle sign, if present
 916         if (firstChar == '-') {
 917             negative = true;
 918             index++;
 919         } else if (firstChar == '+')
 920             index++;
 921 
 922         // Handle radix specifier, if present
 923         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
 924             index += 2;
 925             radix = 16;
 926         }
 927         else if (nm.startsWith("#", index)) {
 928             index ++;
 929             radix = 16;
 930         }
 931         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
 932             index ++;
 933             radix = 8;
 934         }
 935 
 936         if (nm.startsWith("-", index) || nm.startsWith("+", index))
 937             throw new NumberFormatException("Sign character in wrong position");
 938 
 939         try {
 940             result = Integer.valueOf(nm.substring(index), radix);
 941             result = negative ? new Integer(-result.intValue()) : result;
 942         } catch (NumberFormatException e) {
 943             // If number is Integer.MIN_VALUE, we'll end up here. The next line
 944             // handles this case, and causes any genuine format error to be
 945             // rethrown.
 946             String constant = negative ? ("-" + nm.substring(index))
 947                                        : nm.substring(index);
 948             result = Integer.valueOf(constant, radix);
 949         }
 950         return result;
 951     }
 952 
 953     /**
 954      * Compares two {@code Integer} objects numerically.
 955      *
 956      * @param   anotherInteger   the {@code Integer} to be compared.
 957      * @return  the value {@code 0} if this {@code Integer} is
 958      *          equal to the argument {@code Integer}; a value less than
 959      *          {@code 0} if this {@code Integer} is numerically less
 960      *          than the argument {@code Integer}; and a value greater
 961      *          than {@code 0} if this {@code Integer} is numerically
 962      *           greater than the argument {@code Integer} (signed
 963      *           comparison).
 964      * @since   1.2
 965      */
 966     public int compareTo(Integer anotherInteger) {
 967         int thisVal = this.value;
 968         int anotherVal = anotherInteger.value;
 969         return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 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 }