1 /*
   2  * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Native;
  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     @Native 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     @Native 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     @SuppressWarnings("unchecked")
  72     public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
  73 
  74     /**
  75      * All possible chars for representing a number as a String
  76      */
  77     final static char[] digits = {
  78         '0' , '1' , '2' , '3' , '4' , '5' ,
  79         '6' , '7' , '8' , '9' , 'a' , 'b' ,
  80         'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
  81         'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
  82         'o' , 'p' , 'q' , 'r' , 's' , 't' ,
  83         'u' , 'v' , 'w' , 'x' , 'y' , 'z'
  84     };
  85 
  86     /**
  87      * Returns a string representation of the first argument in the
  88      * radix specified by the second argument.
  89      *
  90      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
  91      * or larger than {@code Character.MAX_RADIX}, then the radix
  92      * {@code 10} is used instead.
  93      *
  94      * <p>If the first argument is negative, the first element of the
  95      * result is the ASCII minus character {@code '-'}
  96      * ({@code '\u005Cu002D'}). If the first argument is not
  97      * negative, no sign character appears in the result.
  98      *
  99      * <p>The remaining characters of the result represent the magnitude
 100      * of the first argument. If the magnitude is zero, it is
 101      * represented by a single zero character {@code '0'}
 102      * ({@code '\u005Cu0030'}); otherwise, the first character of
 103      * the representation of the magnitude will not be the zero
 104      * character.  The following ASCII characters are used as digits:
 105      *
 106      * <blockquote>
 107      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
 108      * </blockquote>
 109      *
 110      * These are {@code '\u005Cu0030'} through
 111      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 112      * {@code '\u005Cu007A'}. If {@code radix} is
 113      * <var>N</var>, then the first <var>N</var> of these characters
 114      * are used as radix-<var>N</var> digits in the order shown. Thus,
 115      * the digits for hexadecimal (radix 16) are
 116      * {@code 0123456789abcdef}. If uppercase letters are
 117      * desired, the {@link java.lang.String#toUpperCase()} method may
 118      * be called on the result:
 119      *
 120      * <blockquote>
 121      *  {@code Integer.toString(n, 16).toUpperCase()}
 122      * </blockquote>
 123      *
 124      * @param   i       an integer to be converted to a string.
 125      * @param   radix   the radix to use in the string representation.
 126      * @return  a string representation of the argument in the specified radix.
 127      * @see     java.lang.Character#MAX_RADIX
 128      * @see     java.lang.Character#MIN_RADIX
 129      */
 130     public static String toString(int i, int radix) {
 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 first argument as an
 162      * unsigned integer value in the radix specified by the second
 163      * argument.
 164      *
 165      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 166      * or larger than {@code Character.MAX_RADIX}, then the radix
 167      * {@code 10} is used instead.
 168      *
 169      * <p>Note that since the first argument is treated as an unsigned
 170      * value, no leading sign character is printed.
 171      *
 172      * <p>If the magnitude is zero, it is represented by a single zero
 173      * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
 174      * the first character of the representation of the magnitude will
 175      * not be the zero character.
 176      *
 177      * <p>The behavior of radixes and the characters used as digits
 178      * are the same as {@link #toString(int, int) toString}.
 179      *
 180      * @param   i       an integer to be converted to an unsigned string.
 181      * @param   radix   the radix to use in the string representation.
 182      * @return  an unsigned string representation of the argument in the specified radix.
 183      * @see     #toString(int, int)
 184      * @since 1.8
 185      */
 186     public static String toUnsignedString(int i, int radix) {
 187         return Long.toUnsignedString(toUnsignedLong(i), radix);
 188     }
 189 
 190     /**
 191      * Returns a string representation of the integer argument as an
 192      * unsigned integer in base&nbsp;16.
 193      *
 194      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 195      * if the argument is negative; otherwise, it is equal to the
 196      * argument.  This value is converted to a string of ASCII digits
 197      * in hexadecimal (base&nbsp;16) with no extra leading
 198      * {@code 0}s.
 199      *
 200      * <p>The value of the argument can be recovered from the returned
 201      * string {@code s} by calling {@link
 202      * Integer#parseUnsignedInt(String, int)
 203      * Integer.parseUnsignedInt(s, 16)}.
 204      *
 205      * <p>If the unsigned magnitude is zero, it is represented by a
 206      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 207      * otherwise, the first character of the representation of the
 208      * unsigned magnitude will not be the zero character. The
 209      * following characters are used as hexadecimal digits:
 210      *
 211      * <blockquote>
 212      *  {@code 0123456789abcdef}
 213      * </blockquote>
 214      *
 215      * These are the characters {@code '\u005Cu0030'} through
 216      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 217      * {@code '\u005Cu0066'}. If uppercase letters are
 218      * desired, the {@link java.lang.String#toUpperCase()} method may
 219      * be called on the result:
 220      *
 221      * <blockquote>
 222      *  {@code Integer.toHexString(n).toUpperCase()}
 223      * </blockquote>
 224      *
 225      * @param   i   an integer to be converted to a string.
 226      * @return  the string representation of the unsigned integer value
 227      *          represented by the argument in hexadecimal (base&nbsp;16).
 228      * @see #parseUnsignedInt(String, int)
 229      * @see #toUnsignedString(int, int)
 230      * @since   JDK1.0.2
 231      */
 232     public static String toHexString(int i) {
 233         return toUnsignedString0(i, 4);
 234     }
 235 
 236     /**
 237      * Returns a string representation of the integer argument as an
 238      * unsigned integer in base&nbsp;8.
 239      *
 240      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 241      * if the argument is negative; otherwise, it is equal to the
 242      * argument.  This value is converted to a string of ASCII digits
 243      * in octal (base&nbsp;8) with no extra leading {@code 0}s.
 244      *
 245      * <p>The value of the argument can be recovered from the returned
 246      * string {@code s} by calling {@link
 247      * Integer#parseUnsignedInt(String, int)
 248      * Integer.parseUnsignedInt(s, 8)}.
 249      *
 250      * <p>If the unsigned magnitude is zero, it is represented by a
 251      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 252      * otherwise, the first character of the representation of the
 253      * unsigned magnitude will not be the zero character. The
 254      * following characters are used as octal digits:
 255      *
 256      * <blockquote>
 257      * {@code 01234567}
 258      * </blockquote>
 259      *
 260      * These are the characters {@code '\u005Cu0030'} through
 261      * {@code '\u005Cu0037'}.
 262      *
 263      * @param   i   an integer to be converted to a string.
 264      * @return  the string representation of the unsigned integer value
 265      *          represented by the argument in octal (base&nbsp;8).
 266      * @see #parseUnsignedInt(String, int)
 267      * @see #toUnsignedString(int, int)
 268      * @since   JDK1.0.2
 269      */
 270     public static String toOctalString(int i) {
 271         return toUnsignedString0(i, 3);
 272     }
 273 
 274     /**
 275      * Returns a string representation of the integer argument as an
 276      * unsigned integer in base&nbsp;2.
 277      *
 278      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 279      * if the argument is negative; otherwise it is equal to the
 280      * argument.  This value is converted to a string of ASCII digits
 281      * in binary (base&nbsp;2) with no extra leading {@code 0}s.
 282      *
 283      * <p>The value of the argument can be recovered from the returned
 284      * string {@code s} by calling {@link
 285      * Integer#parseUnsignedInt(String, int)
 286      * Integer.parseUnsignedInt(s, 2)}.
 287      *
 288      * <p>If the unsigned magnitude is zero, it is represented by a
 289      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 290      * otherwise, the first character of the representation of the
 291      * unsigned magnitude will not be the zero character. The
 292      * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
 293      * '1'} ({@code '\u005Cu0031'}) are used as binary digits.
 294      *
 295      * @param   i   an integer to be converted to a string.
 296      * @return  the string representation of the unsigned integer value
 297      *          represented by the argument in binary (base&nbsp;2).
 298      * @see #parseUnsignedInt(String, int)
 299      * @see #toUnsignedString(int, int)
 300      * @since   JDK1.0.2
 301      */
 302     public static String toBinaryString(int i) {
 303         return toUnsignedString0(i, 1);
 304     }
 305 
 306     /**
 307      * Convert the integer to an unsigned number.
 308      */
 309     private static String toUnsignedString0(int val, int shift) {
 310         // assert shift > 0 && shift <=5 : "Illegal shift value";
 311         int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
 312         int chars = Math.max(((mag + (shift - 1)) / shift), 1);
 313         char[] buf = new char[chars];
 314 
 315         formatUnsignedInt(val, shift, buf, 0, chars);
 316 
 317         // Use special constructor which takes over "buf".
 318         return new String(buf, true);
 319     }
 320 
 321     /**
 322      * Format an {@code int} (treated as unsigned) into a character buffer. If
 323      * {@code len} exceeds the formatted ASCII representation of {@code val},
 324      * {@code buf} will be padded with leading zeroes.
 325      *
 326      * @param val the unsigned int to format
 327      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 328      * @param buf the character buffer to write to
 329      * @param offset the offset in the destination buffer to start at
 330      * @param len the number of characters to write
 331      */
 332      static void formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
 333         // assert shift > 0 && shift <=5 : "Illegal shift value";
 334         // assert offset >= 0 && offset < buf.length : "illegal offset";
 335         // assert len > 0 && (offset + len) <= buf.length : "illegal length";
 336         int charPos = offset + len;
 337         int radix = 1 << shift;
 338         int mask = radix - 1;
 339         do {
 340             buf[--charPos] = Integer.digits[val & mask];
 341             val >>>= shift;
 342         } while (charPos > offset);
 343     }
 344 
 345     final static char [] DigitTens = {
 346         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
 347         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
 348         '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
 349         '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
 350         '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
 351         '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
 352         '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
 353         '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
 354         '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
 355         '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
 356         } ;
 357 
 358     final static char [] DigitOnes = {
 359         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 360         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 361         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 362         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 363         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 364         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 365         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 366         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 367         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 368         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 369         } ;
 370 
 371         // I use the "invariant division by multiplication" trick to
 372         // accelerate Integer.toString.  In particular we want to
 373         // avoid division by 10.
 374         //
 375         // The "trick" has roughly the same performance characteristics
 376         // as the "classic" Integer.toString code on a non-JIT VM.
 377         // The trick avoids .rem and .div calls but has a longer code
 378         // path and is thus dominated by dispatch overhead.  In the
 379         // JIT case the dispatch overhead doesn't exist and the
 380         // "trick" is considerably faster than the classic code.
 381         //
 382         // TODO-FIXME: convert (x * 52429) into the equiv shift-add
 383         // sequence.
 384         //
 385         // RE:  Division by Invariant Integers using Multiplication
 386         //      T Gralund, P Montgomery
 387         //      ACM PLDI 1994
 388         //
 389 
 390     /**
 391      * Returns a {@code String} object representing the
 392      * specified integer. The argument is converted to signed decimal
 393      * representation and returned as a string, exactly as if the
 394      * argument and radix 10 were given as arguments to the {@link
 395      * #toString(int, int)} method.
 396      *
 397      * @param   i   an integer to be converted.
 398      * @return  a string representation of the argument in base&nbsp;10.
 399      */
 400     public static String toString(int i) {
 401         if (i == Integer.MIN_VALUE)
 402             return "-2147483648";
 403         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
 404         char[] buf = new char[size];
 405         getChars(i, size, buf);
 406         return new String(buf, true);
 407     }
 408 
 409     /**
 410      * Returns a string representation of the argument as an unsigned
 411      * decimal value.
 412      *
 413      * The argument is converted to unsigned decimal representation
 414      * and returned as a string exactly as if the argument and radix
 415      * 10 were given as arguments to the {@link #toUnsignedString(int,
 416      * int)} method.
 417      *
 418      * @param   i  an integer to be converted to an unsigned string.
 419      * @return  an unsigned string representation of the argument.
 420      * @see     #toUnsignedString(int, int)
 421      * @since 1.8
 422      */
 423     public static String toUnsignedString(int i) {
 424         return Long.toString(toUnsignedLong(i));
 425     }
 426 
 427     /**
 428      * Places characters representing the integer i into the
 429      * character array buf. The characters are placed into
 430      * the buffer backwards starting with the least significant
 431      * digit at the specified index (exclusive), and working
 432      * backwards from there.
 433      *
 434      * Will fail if i == Integer.MIN_VALUE
 435      */
 436     static void getChars(int i, int index, char[] buf) {
 437         int q, r;
 438         int charPos = index;
 439         char sign = 0;
 440 
 441         if (i < 0) {
 442             sign = '-';
 443             i = -i;
 444         }
 445 
 446         // Generate two digits per iteration
 447         while (i >= 65536) {
 448             q = i / 100;
 449         // really: r = i - (q * 100);
 450             r = i - ((q << 6) + (q << 5) + (q << 2));
 451             i = q;
 452             buf [--charPos] = DigitOnes[r];
 453             buf [--charPos] = DigitTens[r];
 454         }
 455 
 456         // Fall thru to fast mode for smaller numbers
 457         // assert(i <= 65536, i);
 458         for (;;) {
 459             q = (i * 52429) >>> (16+3);
 460             r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
 461             buf [--charPos] = digits [r];
 462             i = q;
 463             if (i == 0) break;
 464         }
 465         if (sign != 0) {
 466             buf [--charPos] = sign;
 467         }
 468     }
 469 
 470     final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
 471                                       99999999, 999999999, Integer.MAX_VALUE };
 472 
 473     // Requires positive x
 474     static int stringSize(int x) {
 475         for (int i=0; ; i++)
 476             if (x <= sizeTable[i])
 477                 return i+1;
 478     }
 479 
 480     /**
 481      * Parses the string argument as a signed integer in the radix
 482      * specified by the second argument. The characters in the string
 483      * must all be digits of the specified radix (as determined by
 484      * whether {@link java.lang.Character#digit(char, int)} returns a
 485      * nonnegative value), except that the first character may be an
 486      * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
 487      * indicate a negative value or an ASCII plus sign {@code '+'}
 488      * ({@code '\u005Cu002B'}) to indicate a positive value. The
 489      * resulting integer value is returned.
 490      *
 491      * <p>An exception of type {@code NumberFormatException} is
 492      * thrown if any of the following situations occurs:
 493      * <ul>
 494      * <li>The first argument is {@code null} or is a string of
 495      * length zero.
 496      *
 497      * <li>The radix is either smaller than
 498      * {@link java.lang.Character#MIN_RADIX} or
 499      * larger than {@link java.lang.Character#MAX_RADIX}.
 500      *
 501      * <li>Any character of the string is not a digit of the specified
 502      * radix, except that the first character may be a minus sign
 503      * {@code '-'} ({@code '\u005Cu002D'}) or plus sign
 504      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 505      * string is longer than length 1.
 506      *
 507      * <li>The value represented by the string is not a value of type
 508      * {@code int}.
 509      * </ul>
 510      *
 511      * <p>Examples:
 512      * <blockquote><pre>
 513      * parseInt("0", 10) returns 0
 514      * parseInt("473", 10) returns 473
 515      * parseInt("+42", 10) returns 42
 516      * parseInt("-0", 10) returns 0
 517      * parseInt("-FF", 16) returns -255
 518      * parseInt("1100110", 2) returns 102
 519      * parseInt("2147483647", 10) returns 2147483647
 520      * parseInt("-2147483648", 10) returns -2147483648
 521      * parseInt("2147483648", 10) throws a NumberFormatException
 522      * parseInt("99", 8) throws a NumberFormatException
 523      * parseInt("Kona", 10) throws a NumberFormatException
 524      * parseInt("Kona", 27) returns 411787
 525      * </pre></blockquote>
 526      *
 527      * @param      s   the {@code String} containing the integer
 528      *                  representation to be parsed
 529      * @param      radix   the radix to be used while parsing {@code s}.
 530      * @return     the integer represented by the string argument in the
 531      *             specified radix.
 532      * @exception  NumberFormatException if the {@code String}
 533      *             does not contain a parsable {@code int}.
 534      */
 535     public static int parseInt(String s, int radix)
 536                 throws NumberFormatException
 537     {
 538         /*
 539          * WARNING: This method may be invoked early during VM initialization
 540          * before IntegerCache is initialized. Care must be taken to not use
 541          * the valueOf method.
 542          */
 543 
 544         if (s == null) {
 545             throw new NumberFormatException("null");
 546         }
 547 
 548         if (radix < Character.MIN_RADIX) {
 549             throw new NumberFormatException("radix " + radix +
 550                                             " less than Character.MIN_RADIX");
 551         }
 552 
 553         if (radix > Character.MAX_RADIX) {
 554             throw new NumberFormatException("radix " + radix +
 555                                             " greater than Character.MAX_RADIX");
 556         }
 557 
 558         int result = 0;
 559         boolean negative = false;
 560         int i = 0, len = s.length();
 561         int limit = -Integer.MAX_VALUE;
 562         int multmin;
 563         int digit;
 564 
 565         if (len > 0) {
 566             char firstChar = s.charAt(0);
 567             if (firstChar < '0') { // Possible leading "+" or "-"
 568                 if (firstChar == '-') {
 569                     negative = true;
 570                     limit = Integer.MIN_VALUE;
 571                 } else if (firstChar != '+')
 572                     throw NumberFormatException.forInputString(s);
 573 
 574                 if (len == 1) // Cannot have lone "+" or "-"
 575                     throw NumberFormatException.forInputString(s);
 576                 i++;
 577             }
 578             multmin = limit / radix;
 579             while (i < len) {
 580                 // Accumulating negatively avoids surprises near MAX_VALUE
 581                 digit = Character.digit(s.charAt(i++),radix);
 582                 if (digit < 0) {
 583                     throw NumberFormatException.forInputString(s);
 584                 }
 585                 if (result < multmin) {
 586                     throw NumberFormatException.forInputString(s);
 587                 }
 588                 result *= radix;
 589                 if (result < limit + digit) {
 590                     throw NumberFormatException.forInputString(s);
 591                 }
 592                 result -= digit;
 593             }
 594         } else {
 595             throw NumberFormatException.forInputString(s);
 596         }
 597         return negative ? result : -result;
 598     }
 599 
 600     /**
 601      * Parses the string argument as a signed decimal integer. The
 602      * characters in the string must all be decimal digits, except
 603      * that the first character may be an ASCII minus sign {@code '-'}
 604      * ({@code '\u005Cu002D'}) to indicate a negative value or an
 605      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 606      * indicate a positive value. The resulting integer value is
 607      * returned, exactly as if the argument and the radix 10 were
 608      * given as arguments to the {@link #parseInt(java.lang.String,
 609      * int)} method.
 610      *
 611      * @param s    a {@code String} containing the {@code int}
 612      *             representation to be parsed
 613      * @return     the integer value represented by the argument in decimal.
 614      * @exception  NumberFormatException  if the string does not contain a
 615      *               parsable integer.
 616      */
 617     public static int parseInt(String s) throws NumberFormatException {
 618         return parseInt(s,10);
 619     }
 620 
 621     /**
 622      * Parses the string argument as an unsigned integer in the radix
 623      * specified by the second argument.  An unsigned integer maps the
 624      * values usually associated with negative numbers to positive
 625      * numbers larger than {@code MAX_VALUE}.
 626      *
 627      * The characters in the string must all be digits of the
 628      * specified radix (as determined by whether {@link
 629      * java.lang.Character#digit(char, int)} returns a nonnegative
 630      * value), except that the first character may be an ASCII plus
 631      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 632      * integer value is returned.
 633      *
 634      * <p>An exception of type {@code NumberFormatException} is
 635      * thrown if any of the following situations occurs:
 636      * <ul>
 637      * <li>The first argument is {@code null} or is a string of
 638      * length zero.
 639      *
 640      * <li>The radix is either smaller than
 641      * {@link java.lang.Character#MIN_RADIX} or
 642      * larger than {@link java.lang.Character#MAX_RADIX}.
 643      *
 644      * <li>Any character of the string is not a digit of the specified
 645      * radix, except that the first character may be a plus sign
 646      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 647      * string is longer than length 1.
 648      *
 649      * <li>The value represented by the string is larger than the
 650      * largest unsigned {@code int}, 2<sup>32</sup>-1.
 651      *
 652      * </ul>
 653      *
 654      *
 655      * @param      s   the {@code String} containing the unsigned integer
 656      *                  representation to be parsed
 657      * @param      radix   the radix to be used while parsing {@code s}.
 658      * @return     the integer represented by the string argument in the
 659      *             specified radix.
 660      * @throws     NumberFormatException if the {@code String}
 661      *             does not contain a parsable {@code int}.
 662      * @since 1.8
 663      */
 664     public static int parseUnsignedInt(String s, int radix)
 665                 throws NumberFormatException {
 666         if (s == null)  {
 667             throw new NumberFormatException("null");
 668         }
 669 
 670         int len = s.length();
 671         if (len > 0) {
 672             char firstChar = s.charAt(0);
 673             if (firstChar == '-') {
 674                 throw new
 675                     NumberFormatException(String.format("Illegal leading minus sign " +
 676                                                        "on unsigned string %s.", s));
 677             } else {
 678                 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
 679                     (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
 680                     return parseInt(s, radix);
 681                 } else {
 682                     long ell = Long.parseLong(s, radix);
 683                     if ((ell & 0xffff_ffff_0000_0000L) == 0) {
 684                         return (int) ell;
 685                     } else {
 686                         throw new
 687                             NumberFormatException(String.format("String value %s exceeds " +
 688                                                                 "range of unsigned int.", s));
 689                     }
 690                 }
 691             }
 692         } else {
 693             throw NumberFormatException.forInputString(s);
 694         }
 695     }
 696 
 697     /**
 698      * Parses the string argument as an unsigned decimal integer. The
 699      * characters in the string must all be decimal digits, except
 700      * that the first character may be an an ASCII plus sign {@code
 701      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 702      * is returned, exactly as if the argument and the radix 10 were
 703      * given as arguments to the {@link
 704      * #parseUnsignedInt(java.lang.String, int)} method.
 705      *
 706      * @param s   a {@code String} containing the unsigned {@code int}
 707      *            representation to be parsed
 708      * @return    the unsigned integer value represented by the argument in decimal.
 709      * @throws    NumberFormatException  if the string does not contain a
 710      *            parsable unsigned integer.
 711      * @since 1.8
 712      */
 713     public static int parseUnsignedInt(String s) throws NumberFormatException {
 714         return parseUnsignedInt(s, 10);
 715     }
 716 
 717     /**
 718      * Returns an {@code Integer} object holding the value
 719      * extracted from the specified {@code String} when parsed
 720      * with the radix given by the second argument. The first argument
 721      * is interpreted as representing a signed integer in the radix
 722      * specified by the second argument, exactly as if the arguments
 723      * were given to the {@link #parseInt(java.lang.String, int)}
 724      * method. The result is an {@code Integer} object that
 725      * represents the integer value specified by the string.
 726      *
 727      * <p>In other words, this method returns an {@code Integer}
 728      * object equal to the value of:
 729      *
 730      * <blockquote>
 731      *  {@code new Integer(Integer.parseInt(s, radix))}
 732      * </blockquote>
 733      *
 734      * @param      s   the string to be parsed.
 735      * @param      radix the radix to be used in interpreting {@code s}
 736      * @return     an {@code Integer} object holding the value
 737      *             represented by the string argument in the specified
 738      *             radix.
 739      * @exception NumberFormatException if the {@code String}
 740      *            does not contain a parsable {@code int}.
 741      */
 742     public static Integer valueOf(String s, int radix) throws NumberFormatException {
 743         return Integer.valueOf(parseInt(s,radix));
 744     }
 745 
 746     /**
 747      * Returns an {@code Integer} object holding the
 748      * value of the specified {@code String}. The argument is
 749      * interpreted as representing a signed decimal integer, exactly
 750      * as if the argument were given to the {@link
 751      * #parseInt(java.lang.String)} method. The result is an
 752      * {@code Integer} object that represents the integer value
 753      * specified by the string.
 754      *
 755      * <p>In other words, this method returns an {@code Integer}
 756      * object equal to the value of:
 757      *
 758      * <blockquote>
 759      *  {@code new Integer(Integer.parseInt(s))}
 760      * </blockquote>
 761      *
 762      * @param      s   the string to be parsed.
 763      * @return     an {@code Integer} object holding the value
 764      *             represented by the string argument.
 765      * @exception  NumberFormatException  if the string cannot be parsed
 766      *             as an integer.
 767      */
 768     public static Integer valueOf(String s) throws NumberFormatException {
 769         return Integer.valueOf(parseInt(s, 10));
 770     }
 771 
 772     /**
 773      * Cache to support the object identity semantics of autoboxing for values between
 774      * -128 and 127 (inclusive) as required by JLS.
 775      *
 776      * The cache is initialized on first usage.  The size of the cache
 777      * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
 778      * During VM initialization, java.lang.Integer.IntegerCache.high property
 779      * may be set and saved in the private system properties in the
 780      * sun.misc.VM class.
 781      */
 782 
 783     private static class IntegerCache {
 784         static final int low = -128;
 785         static final int high;
 786         static final Integer cache[];
 787 
 788         static {
 789             // high value may be configured by property
 790             int h = 127;
 791             String integerCacheHighPropValue =
 792                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 793             if (integerCacheHighPropValue != null) {
 794                 try {
 795                     int i = parseInt(integerCacheHighPropValue);
 796                     i = Math.max(i, 127);
 797                     // Maximum array size is Integer.MAX_VALUE
 798                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
 799                 } catch( NumberFormatException nfe) {
 800                     // If the property cannot be parsed into an int, ignore it.
 801                 }
 802             }
 803             high = h;
 804 
 805             cache = new Integer[(high - low) + 1];
 806             int j = low;
 807             for(int k = 0; k < cache.length; k++)
 808                 cache[k] = new Integer(j++);
 809 
 810             // range [-128, 127] must be interned (JLS7 5.1.7)
 811             assert IntegerCache.high >= 127;
 812         }
 813 
 814         private IntegerCache() {}
 815     }
 816 
 817     /**
 818      * Returns an {@code Integer} instance representing the specified
 819      * {@code int} value.  If a new {@code Integer} instance is not
 820      * required, this method should generally be used in preference to
 821      * the constructor {@link #Integer(int)}, as this method is likely
 822      * to yield significantly better space and time performance by
 823      * caching frequently requested values.
 824      *
 825      * This method will always cache values in the range -128 to 127,
 826      * inclusive, and may cache other values outside of this range.
 827      *
 828      * @param  i an {@code int} value.
 829      * @return an {@code Integer} instance representing {@code i}.
 830      * @since  1.5
 831      */
 832     public static Integer valueOf(int i) {
 833         if (i >= IntegerCache.low && i <= IntegerCache.high)
 834             return IntegerCache.cache[i + (-IntegerCache.low)];
 835         return new Integer(i);
 836     }
 837 
 838     /**
 839      * The value of the {@code Integer}.
 840      *
 841      * @serial
 842      */
 843     private final int value;
 844 
 845     /**
 846      * Constructs a newly allocated {@code Integer} object that
 847      * represents the specified {@code int} value.
 848      *
 849      * @param   value   the value to be represented by the
 850      *                  {@code Integer} object.
 851      */
 852     public Integer(int value) {
 853         this.value = value;
 854     }
 855 
 856     /**
 857      * Constructs a newly allocated {@code Integer} object that
 858      * represents the {@code int} value indicated by the
 859      * {@code String} parameter. The string is converted to an
 860      * {@code int} value in exactly the manner used by the
 861      * {@code parseInt} method for radix 10.
 862      *
 863      * @param      s   the {@code String} to be converted to an
 864      *                 {@code Integer}.
 865      * @exception  NumberFormatException  if the {@code String} does not
 866      *               contain a parsable integer.
 867      * @see        java.lang.Integer#parseInt(java.lang.String, int)
 868      */
 869     public Integer(String s) throws NumberFormatException {
 870         this.value = parseInt(s, 10);
 871     }
 872 
 873     /**
 874      * Returns the value of this {@code Integer} as a {@code byte}
 875      * after a narrowing primitive conversion.
 876      * @jls 5.1.3 Narrowing Primitive Conversions
 877      */
 878     public byte byteValue() {
 879         return (byte)value;
 880     }
 881 
 882     /**
 883      * Returns the value of this {@code Integer} as a {@code short}
 884      * after a narrowing primitive conversion.
 885      * @jls 5.1.3 Narrowing Primitive Conversions
 886      */
 887     public short shortValue() {
 888         return (short)value;
 889     }
 890 
 891     /**
 892      * Returns the value of this {@code Integer} as an
 893      * {@code int}.
 894      */
 895     public int intValue() {
 896         return value;
 897     }
 898 
 899     /**
 900      * Returns the value of this {@code Integer} as a {@code long}
 901      * after a widening primitive conversion.
 902      * @jls 5.1.2 Widening Primitive Conversions
 903      * @see Integer#toUnsignedLong(int)
 904      */
 905     public long longValue() {
 906         return (long)value;
 907     }
 908 
 909     /**
 910      * Returns the value of this {@code Integer} as a {@code float}
 911      * after a widening primitive conversion.
 912      * @jls 5.1.2 Widening Primitive Conversions
 913      */
 914     public float floatValue() {
 915         return (float)value;
 916     }
 917 
 918     /**
 919      * Returns the value of this {@code Integer} as a {@code double}
 920      * after a widening primitive conversion.
 921      * @jls 5.1.2 Widening Primitive Conversions
 922      */
 923     public double doubleValue() {
 924         return (double)value;
 925     }
 926 
 927     /**
 928      * Returns a {@code String} object representing this
 929      * {@code Integer}'s value. The value is converted to signed
 930      * decimal representation and returned as a string, exactly as if
 931      * the integer value were given as an argument to the {@link
 932      * java.lang.Integer#toString(int)} method.
 933      *
 934      * @return  a string representation of the value of this object in
 935      *          base&nbsp;10.
 936      */
 937     public String toString() {
 938         return toString(value);
 939     }
 940 
 941     /**
 942      * Returns a hash code for this {@code Integer}.
 943      *
 944      * @return  a hash code value for this object, equal to the
 945      *          primitive {@code int} value represented by this
 946      *          {@code Integer} object.
 947      */
 948     @Override
 949     public int hashCode() {
 950         return Integer.hashCode(value);
 951     }
 952 
 953     /**
 954      * Returns a hash code for a {@code int} value; compatible with
 955      * {@code Integer.hashCode()}.
 956      *
 957      * @param value the value to hash
 958      * @since 1.8
 959      *
 960      * @return a hash code value for a {@code int} value.
 961      */
 962     public static int hashCode(int value) {
 963         return value;
 964     }
 965 
 966     /**
 967      * Compares this object to the specified object.  The result is
 968      * {@code true} if and only if the argument is not
 969      * {@code null} and is an {@code Integer} object that
 970      * contains the same {@code int} value as this object.
 971      *
 972      * @param   obj   the object to compare with.
 973      * @return  {@code true} if the objects are the same;
 974      *          {@code false} otherwise.
 975      */
 976     public boolean equals(Object obj) {
 977         if (obj instanceof Integer) {
 978             return value == ((Integer)obj).intValue();
 979         }
 980         return false;
 981     }
 982 
 983     /**
 984      * Determines the integer value of the system property with the
 985      * specified name.
 986      *
 987      * <p>The first argument is treated as the name of a system
 988      * property.  System properties are accessible through the {@link
 989      * java.lang.System#getProperty(java.lang.String)} method. The
 990      * string value of this property is then interpreted as an integer
 991      * value using the grammar supported by {@link Integer#decode decode} and
 992      * an {@code Integer} object representing this value is returned.
 993      *
 994      * <p>If there is no property with the specified name, if the
 995      * specified name is empty or {@code null}, or if the property
 996      * does not have the correct numeric format, then {@code null} is
 997      * returned.
 998      *
 999      * <p>In other words, this method returns an {@code Integer}
1000      * object equal to the value of:
1001      *
1002      * <blockquote>
1003      *  {@code getInteger(nm, null)}
1004      * </blockquote>
1005      *
1006      * @param   nm   property name.
1007      * @return  the {@code Integer} value of the property.
1008      * @throws  SecurityException for the same reasons as
1009      *          {@link System#getProperty(String) System.getProperty}
1010      * @see     java.lang.System#getProperty(java.lang.String)
1011      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1012      */
1013     public static Integer getInteger(String nm) {
1014         return getInteger(nm, null);
1015     }
1016 
1017     /**
1018      * Determines the integer value of the system property with the
1019      * specified name.
1020      *
1021      * <p>The first argument is treated as the name of a system
1022      * property.  System properties are accessible through the {@link
1023      * java.lang.System#getProperty(java.lang.String)} method. The
1024      * string value of this property is then interpreted as an integer
1025      * value using the grammar supported by {@link Integer#decode decode} and
1026      * an {@code Integer} object representing this value is returned.
1027      *
1028      * <p>The second argument is the default value. An {@code Integer} object
1029      * that represents the value of the second argument is returned if there
1030      * is no property of the specified name, if the property does not have
1031      * the correct numeric format, or if the specified name is empty or
1032      * {@code null}.
1033      *
1034      * <p>In other words, this method returns an {@code Integer} object
1035      * equal to the value of:
1036      *
1037      * <blockquote>
1038      *  {@code getInteger(nm, new Integer(val))}
1039      * </blockquote>
1040      *
1041      * but in practice it may be implemented in a manner such as:
1042      *
1043      * <blockquote><pre>
1044      * Integer result = getInteger(nm, null);
1045      * return (result == null) ? new Integer(val) : result;
1046      * </pre></blockquote>
1047      *
1048      * to avoid the unnecessary allocation of an {@code Integer}
1049      * object when the default value is not needed.
1050      *
1051      * @param   nm   property name.
1052      * @param   val   default value.
1053      * @return  the {@code Integer} value of the property.
1054      * @throws  SecurityException for the same reasons as
1055      *          {@link System#getProperty(String) System.getProperty}
1056      * @see     java.lang.System#getProperty(java.lang.String)
1057      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1058      */
1059     public static Integer getInteger(String nm, int val) {
1060         Integer result = getInteger(nm, null);
1061         return (result == null) ? Integer.valueOf(val) : result;
1062     }
1063 
1064     /**
1065      * Returns the integer value of the system property with the
1066      * specified name.  The first argument is treated as the name of a
1067      * system property.  System properties are accessible through the
1068      * {@link java.lang.System#getProperty(java.lang.String)} method.
1069      * The string value of this property is then interpreted as an
1070      * integer value, as per the {@link Integer#decode decode} method,
1071      * and an {@code Integer} object representing this value is
1072      * returned; in summary:
1073      *
1074      * <ul><li>If the property value begins with the two ASCII characters
1075      *         {@code 0x} or the ASCII character {@code #}, not
1076      *      followed by a minus sign, then the rest of it is parsed as a
1077      *      hexadecimal integer exactly as by the method
1078      *      {@link #valueOf(java.lang.String, int)} with radix 16.
1079      * <li>If the property value begins with the ASCII character
1080      *     {@code 0} followed by another character, it is parsed as an
1081      *     octal integer exactly as by the method
1082      *     {@link #valueOf(java.lang.String, int)} with radix 8.
1083      * <li>Otherwise, the property value is parsed as a decimal integer
1084      * exactly as by the method {@link #valueOf(java.lang.String, int)}
1085      * with radix 10.
1086      * </ul>
1087      *
1088      * <p>The second argument is the default value. The default value is
1089      * returned if there is no property of the specified name, if the
1090      * property does not have the correct numeric format, or if the
1091      * specified name is empty or {@code null}.
1092      *
1093      * @param   nm   property name.
1094      * @param   val   default value.
1095      * @return  the {@code Integer} value of the property.
1096      * @throws  SecurityException for the same reasons as
1097      *          {@link System#getProperty(String) System.getProperty}
1098      * @see     System#getProperty(java.lang.String)
1099      * @see     System#getProperty(java.lang.String, java.lang.String)
1100      */
1101     public static Integer getInteger(String nm, Integer val) {
1102         String v = null;
1103         try {
1104             v = System.getProperty(nm);
1105         } catch (IllegalArgumentException | NullPointerException e) {
1106         }
1107         if (v != null) {
1108             try {
1109                 return Integer.decode(v);
1110             } catch (NumberFormatException e) {
1111             }
1112         }
1113         return val;
1114     }
1115 
1116     /**
1117      * Decodes a {@code String} into an {@code Integer}.
1118      * Accepts decimal, hexadecimal, and octal numbers given
1119      * by the following grammar:
1120      *
1121      * <blockquote>
1122      * <dl>
1123      * <dt><i>DecodableString:</i>
1124      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1125      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1126      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1127      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1128      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1129      *
1130      * <dt><i>Sign:</i>
1131      * <dd>{@code -}
1132      * <dd>{@code +}
1133      * </dl>
1134      * </blockquote>
1135      *
1136      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1137      * are as defined in section 3.10.1 of
1138      * <cite>The Java&trade; Language Specification</cite>,
1139      * except that underscores are not accepted between digits.
1140      *
1141      * <p>The sequence of characters following an optional
1142      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1143      * "{@code #}", or leading zero) is parsed as by the {@code
1144      * Integer.parseInt} method with the indicated radix (10, 16, or
1145      * 8).  This sequence of characters must represent a positive
1146      * value or a {@link NumberFormatException} will be thrown.  The
1147      * result is negated if first character of the specified {@code
1148      * String} is the minus sign.  No whitespace characters are
1149      * permitted in the {@code String}.
1150      *
1151      * @param     nm the {@code String} to decode.
1152      * @return    an {@code Integer} object holding the {@code int}
1153      *             value represented by {@code nm}
1154      * @exception NumberFormatException  if the {@code String} does not
1155      *            contain a parsable integer.
1156      * @see java.lang.Integer#parseInt(java.lang.String, int)
1157      */
1158     public static Integer decode(String nm) throws NumberFormatException {
1159         int radix = 10;
1160         int index = 0;
1161         boolean negative = false;
1162         Integer result;
1163 
1164         if (nm.length() == 0)
1165             throw new NumberFormatException("Zero length string");
1166         char firstChar = nm.charAt(0);
1167         // Handle sign, if present
1168         if (firstChar == '-') {
1169             negative = true;
1170             index++;
1171         } else if (firstChar == '+')
1172             index++;
1173 
1174         // Handle radix specifier, if present
1175         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1176             index += 2;
1177             radix = 16;
1178         }
1179         else if (nm.startsWith("#", index)) {
1180             index ++;
1181             radix = 16;
1182         }
1183         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1184             index ++;
1185             radix = 8;
1186         }
1187 
1188         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1189             throw new NumberFormatException("Sign character in wrong position");
1190 
1191         try {
1192             result = Integer.valueOf(nm.substring(index), radix);
1193             result = negative ? Integer.valueOf(-result.intValue()) : result;
1194         } catch (NumberFormatException e) {
1195             // If number is Integer.MIN_VALUE, we'll end up here. The next line
1196             // handles this case, and causes any genuine format error to be
1197             // rethrown.
1198             String constant = negative ? ("-" + nm.substring(index))
1199                                        : nm.substring(index);
1200             result = Integer.valueOf(constant, radix);
1201         }
1202         return result;
1203     }
1204 
1205     /**
1206      * Compares two {@code Integer} objects numerically.
1207      *
1208      * @param   anotherInteger   the {@code Integer} to be compared.
1209      * @return  the value {@code 0} if this {@code Integer} is
1210      *          equal to the argument {@code Integer}; a value less than
1211      *          {@code 0} if this {@code Integer} is numerically less
1212      *          than the argument {@code Integer}; and a value greater
1213      *          than {@code 0} if this {@code Integer} is numerically
1214      *           greater than the argument {@code Integer} (signed
1215      *           comparison).
1216      * @since   1.2
1217      */
1218     public int compareTo(Integer anotherInteger) {
1219         return compare(this.value, anotherInteger.value);
1220     }
1221 
1222     /**
1223      * Compares two {@code int} values numerically.
1224      * The value returned is identical to what would be returned by:
1225      * <pre>
1226      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
1227      * </pre>
1228      *
1229      * @param  x the first {@code int} to compare
1230      * @param  y the second {@code int} to compare
1231      * @return the value {@code 0} if {@code x == y};
1232      *         a value less than {@code 0} if {@code x < y}; and
1233      *         a value greater than {@code 0} if {@code x > y}
1234      * @since 1.7
1235      */
1236     public static int compare(int x, int y) {
1237         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1238     }
1239 
1240     /**
1241      * Compares two {@code int} values numerically treating the values
1242      * as unsigned.
1243      *
1244      * @param  x the first {@code int} to compare
1245      * @param  y the second {@code int} to compare
1246      * @return the value {@code 0} if {@code x == y}; a value less
1247      *         than {@code 0} if {@code x < y} as unsigned values; and
1248      *         a value greater than {@code 0} if {@code x > y} as
1249      *         unsigned values
1250      * @since 1.8
1251      */
1252     public static int compareUnsigned(int x, int y) {
1253         return compare(x + MIN_VALUE, y + MIN_VALUE);
1254     }
1255 
1256     /**
1257      * Converts the argument to a {@code long} by an unsigned
1258      * conversion.  In an unsigned conversion to a {@code long}, the
1259      * high-order 32 bits of the {@code long} are zero and the
1260      * low-order 32 bits are equal to the bits of the integer
1261      * argument.
1262      *
1263      * Consequently, zero and positive {@code int} values are mapped
1264      * to a numerically equal {@code long} value and negative {@code
1265      * int} values are mapped to a {@code long} value equal to the
1266      * input plus 2<sup>32</sup>.
1267      *
1268      * @param  x the value to convert to an unsigned {@code long}
1269      * @return the argument converted to {@code long} by an unsigned
1270      *         conversion
1271      * @since 1.8
1272      */
1273     public static long toUnsignedLong(int x) {
1274         return ((long) x) & 0xffffffffL;
1275     }
1276 
1277     /**
1278      * Returns the unsigned quotient of dividing the first argument by
1279      * the second where each argument and the result is interpreted as
1280      * an unsigned value.
1281      *
1282      * <p>Note that in two's complement arithmetic, the three other
1283      * basic arithmetic operations of add, subtract, and multiply are
1284      * bit-wise identical if the two operands are regarded as both
1285      * being signed or both being unsigned.  Therefore separate {@code
1286      * addUnsigned}, etc. methods are not provided.
1287      *
1288      * @param dividend the value to be divided
1289      * @param divisor the value doing the dividing
1290      * @return the unsigned quotient of the first argument divided by
1291      * the second argument
1292      * @see #remainderUnsigned
1293      * @since 1.8
1294      */
1295     public static int divideUnsigned(int dividend, int divisor) {
1296         // In lieu of tricky code, for now just use long arithmetic.
1297         return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
1298     }
1299 
1300     /**
1301      * Returns the unsigned remainder from dividing the first argument
1302      * by the second where each argument and the result is interpreted
1303      * as an unsigned value.
1304      *
1305      * @param dividend the value to be divided
1306      * @param divisor the value doing the dividing
1307      * @return the unsigned remainder of the first argument divided by
1308      * the second argument
1309      * @see #divideUnsigned
1310      * @since 1.8
1311      */
1312     public static int remainderUnsigned(int dividend, int divisor) {
1313         // In lieu of tricky code, for now just use long arithmetic.
1314         return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
1315     }
1316 
1317 
1318     // Bit twiddling
1319 
1320     /**
1321      * The number of bits used to represent an {@code int} value in two's
1322      * complement binary form.
1323      *
1324      * @since 1.5
1325      */
1326     @Native public static final int SIZE = 32;
1327 
1328     /**
1329      * The number of bytes used to represent a {@code int} value in two's
1330      * complement binary form.
1331      *
1332      * @since 1.8
1333      */
1334     public static final int BYTES = SIZE / Byte.SIZE;
1335 
1336     /**
1337      * Returns an {@code int} value with at most a single one-bit, in the
1338      * position of the highest-order ("leftmost") one-bit in the specified
1339      * {@code int} value.  Returns zero if the specified value has no
1340      * one-bits in its two's complement binary representation, that is, if it
1341      * is equal to zero.
1342      *
1343      * @param i the value whose highest one bit is to be computed
1344      * @return an {@code int} value with a single one-bit, in the position
1345      *     of the highest-order one-bit in the specified value, or zero if
1346      *     the specified value is itself equal to zero.
1347      * @since 1.5
1348      */
1349     public static int highestOneBit(int i) {
1350         // HD, Figure 3-1
1351         i |= (i >>  1);
1352         i |= (i >>  2);
1353         i |= (i >>  4);
1354         i |= (i >>  8);
1355         i |= (i >> 16);
1356         return i - (i >>> 1);
1357     }
1358 
1359     /**
1360      * Returns an {@code int} value with at most a single one-bit, in the
1361      * position of the lowest-order ("rightmost") one-bit in the specified
1362      * {@code int} value.  Returns zero if the specified value has no
1363      * one-bits in its two's complement binary representation, that is, if it
1364      * is equal to zero.
1365      *
1366      * @param i the value whose lowest one bit is to be computed
1367      * @return an {@code int} value with a single one-bit, in the position
1368      *     of the lowest-order one-bit in the specified value, or zero if
1369      *     the specified value is itself equal to zero.
1370      * @since 1.5
1371      */
1372     public static int lowestOneBit(int i) {
1373         // HD, Section 2-1
1374         return i & -i;
1375     }
1376 
1377     /**
1378      * Returns the number of zero bits preceding the highest-order
1379      * ("leftmost") one-bit in the two's complement binary representation
1380      * of the specified {@code int} value.  Returns 32 if the
1381      * specified value has no one-bits in its two's complement representation,
1382      * in other words if it is equal to zero.
1383      *
1384      * <p>Note that this method is closely related to the logarithm base 2.
1385      * For all positive {@code int} values x:
1386      * <ul>
1387      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1388      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1389      * </ul>
1390      *
1391      * @param i the value whose number of leading zeros is to be computed
1392      * @return the number of zero bits preceding the highest-order
1393      *     ("leftmost") one-bit in the two's complement binary representation
1394      *     of the specified {@code int} value, or 32 if the value
1395      *     is equal to zero.
1396      * @since 1.5
1397      */
1398     public static int numberOfLeadingZeros(int i) {
1399         // HD, Figure 5-6
1400         if (i == 0)
1401             return 32;
1402         int n = 1;
1403         if (i >>> 16 == 0) { n += 16; i <<= 16; }
1404         if (i >>> 24 == 0) { n +=  8; i <<=  8; }
1405         if (i >>> 28 == 0) { n +=  4; i <<=  4; }
1406         if (i >>> 30 == 0) { n +=  2; i <<=  2; }
1407         n -= i >>> 31;
1408         return n;
1409     }
1410 
1411     /**
1412      * Returns the number of zero bits following the lowest-order ("rightmost")
1413      * one-bit in the two's complement binary representation of the specified
1414      * {@code int} value.  Returns 32 if the specified value has no
1415      * one-bits in its two's complement representation, in other words if it is
1416      * equal to zero.
1417      *
1418      * @param i the value whose number of trailing zeros is to be computed
1419      * @return the number of zero bits following the lowest-order ("rightmost")
1420      *     one-bit in the two's complement binary representation of the
1421      *     specified {@code int} value, or 32 if the value is equal
1422      *     to zero.
1423      * @since 1.5
1424      */
1425     public static int numberOfTrailingZeros(int i) {
1426         // HD, Figure 5-14
1427         int y;
1428         if (i == 0) return 32;
1429         int n = 31;
1430         y = i <<16; if (y != 0) { n = n -16; i = y; }
1431         y = i << 8; if (y != 0) { n = n - 8; i = y; }
1432         y = i << 4; if (y != 0) { n = n - 4; i = y; }
1433         y = i << 2; if (y != 0) { n = n - 2; i = y; }
1434         return n - ((i << 1) >>> 31);
1435     }
1436 
1437     /**
1438      * Returns the number of one-bits in the two's complement binary
1439      * representation of the specified {@code int} value.  This function is
1440      * sometimes referred to as the <i>population count</i>.
1441      *
1442      * @param i the value whose bits are to be counted
1443      * @return the number of one-bits in the two's complement binary
1444      *     representation of the specified {@code int} value.
1445      * @since 1.5
1446      */
1447     public static int bitCount(int i) {
1448         // HD, Figure 5-2
1449         i = i - ((i >>> 1) & 0x55555555);
1450         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1451         i = (i + (i >>> 4)) & 0x0f0f0f0f;
1452         i = i + (i >>> 8);
1453         i = i + (i >>> 16);
1454         return i & 0x3f;
1455     }
1456 
1457     /**
1458      * Returns the value obtained by rotating the two's complement binary
1459      * representation of the specified {@code int} value left by the
1460      * specified number of bits.  (Bits shifted out of the left hand, or
1461      * high-order, side reenter on the right, or low-order.)
1462      *
1463      * <p>Note that left rotation with a negative distance is equivalent to
1464      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1465      * distance)}.  Note also that rotation by any multiple of 32 is a
1466      * no-op, so all but the last five bits of the rotation distance can be
1467      * ignored, even if the distance is negative: {@code rotateLeft(val,
1468      * distance) == rotateLeft(val, distance & 0x1F)}.
1469      *
1470      * @param i the value whose bits are to be rotated left
1471      * @param distance the number of bit positions to rotate left
1472      * @return the value obtained by rotating the two's complement binary
1473      *     representation of the specified {@code int} value left by the
1474      *     specified number of bits.
1475      * @since 1.5
1476      */
1477     public static int rotateLeft(int i, int distance) {
1478         return (i << distance) | (i >>> -distance);
1479     }
1480 
1481     /**
1482      * Returns the value obtained by rotating the two's complement binary
1483      * representation of the specified {@code int} value right by the
1484      * specified number of bits.  (Bits shifted out of the right hand, or
1485      * low-order, side reenter on the left, or high-order.)
1486      *
1487      * <p>Note that right rotation with a negative distance is equivalent to
1488      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1489      * distance)}.  Note also that rotation by any multiple of 32 is a
1490      * no-op, so all but the last five bits of the rotation distance can be
1491      * ignored, even if the distance is negative: {@code rotateRight(val,
1492      * distance) == rotateRight(val, distance & 0x1F)}.
1493      *
1494      * @param i the value whose bits are to be rotated right
1495      * @param distance the number of bit positions to rotate right
1496      * @return the value obtained by rotating the two's complement binary
1497      *     representation of the specified {@code int} value right by the
1498      *     specified number of bits.
1499      * @since 1.5
1500      */
1501     public static int rotateRight(int i, int distance) {
1502         return (i >>> distance) | (i << -distance);
1503     }
1504 
1505     /**
1506      * Returns the value obtained by reversing the order of the bits in the
1507      * two's complement binary representation of the specified {@code int}
1508      * value.
1509      *
1510      * @param i the value to be reversed
1511      * @return the value obtained by reversing order of the bits in the
1512      *     specified {@code int} value.
1513      * @since 1.5
1514      */
1515     public static int reverse(int i) {
1516         // HD, Figure 7-1
1517         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1518         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1519         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1520         i = (i << 24) | ((i & 0xff00) << 8) |
1521             ((i >>> 8) & 0xff00) | (i >>> 24);
1522         return i;
1523     }
1524 
1525     /**
1526      * Returns the signum function of the specified {@code int} value.  (The
1527      * return value is -1 if the specified value is negative; 0 if the
1528      * specified value is zero; and 1 if the specified value is positive.)
1529      *
1530      * @param i the value whose signum is to be computed
1531      * @return the signum function of the specified {@code int} value.
1532      * @since 1.5
1533      */
1534     public static int signum(int i) {
1535         // HD, Section 2-7
1536         return (i >> 31) | (-i >>> 31);
1537     }
1538 
1539     /**
1540      * Returns the value obtained by reversing the order of the bytes in the
1541      * two's complement representation of the specified {@code int} value.
1542      *
1543      * @param i the value whose bytes are to be reversed
1544      * @return the value obtained by reversing the bytes in the specified
1545      *     {@code int} value.
1546      * @since 1.5
1547      */
1548     public static int reverseBytes(int i) {
1549         return ((i >>> 24)           ) |
1550                ((i >>   8) &   0xFF00) |
1551                ((i <<   8) & 0xFF0000) |
1552                ((i << 24));
1553     }
1554 
1555     /**
1556      * Adds two integers together as per the + operator.
1557      *
1558      * @param a the first operand
1559      * @param b the second operand
1560      * @return the sum of {@code a} and {@code b}
1561      * @see java.util.function.BinaryOperator
1562      * @since 1.8
1563      */
1564     public static int sum(int a, int b) {
1565         return a + b;
1566     }
1567 
1568     /**
1569      * Returns the greater of two {@code int} values
1570      * as if by calling {@link Math#max(int, int) Math.max}.
1571      *
1572      * @param a the first operand
1573      * @param b the second operand
1574      * @return the greater of {@code a} and {@code b}
1575      * @see java.util.function.BinaryOperator
1576      * @since 1.8
1577      */
1578     public static int max(int a, int b) {
1579         return Math.max(a, b);
1580     }
1581 
1582     /**
1583      * Returns the smaller of two {@code int} values
1584      * as if by calling {@link Math#min(int, int) Math.min}.
1585      *
1586      * @param a the first operand
1587      * @param b the second operand
1588      * @return the smaller of {@code a} and {@code b}
1589      * @see java.util.function.BinaryOperator
1590      * @since 1.8
1591      */
1592     public static int min(int a, int b) {
1593         return Math.min(a, b);
1594     }
1595 
1596     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1597     @Native private static final long serialVersionUID = 1360826667806852920L;
1598 }