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