1 /*
   2  * Copyright (c) 1994, 2016, 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 import java.util.Objects;
  30 import jdk.internal.HotSpotIntrinsicCandidate;
  31 import jdk.internal.misc.VM;
  32 
  33 import static java.lang.String.COMPACT_STRINGS;
  34 import static java.lang.String.LATIN1;
  35 import static java.lang.String.UTF16;
  36 
  37 /**
  38  * The {@code Integer} class wraps a value of the primitive type
  39  * {@code int} in an object. An object of type {@code Integer}
  40  * contains a single field whose type is {@code int}.
  41  *
  42  * <p>In addition, this class provides several methods for converting
  43  * an {@code int} to a {@code String} and a {@code String} to an
  44  * {@code int}, as well as other constants and methods useful when
  45  * dealing with an {@code int}.
  46  *
  47  * <p>Implementation note: The implementations of the "bit twiddling"
  48  * methods (such as {@link #highestOneBit(int) highestOneBit} and
  49  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
  50  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  51  * Delight</i>, (Addison Wesley, 2002).
  52  *
  53  * @author  Lee Boynton
  54  * @author  Arthur van Hoff
  55  * @author  Josh Bloch
  56  * @author  Joseph D. Darcy
  57  * @since 1.0
  58  */
  59 public final class Integer extends Number implements Comparable<Integer> {
  60     /**
  61      * A constant holding the minimum value an {@code int} can
  62      * have, -2<sup>31</sup>.
  63      */
  64     @Native public static final int   MIN_VALUE = 0x80000000;
  65 
  66     /**
  67      * A constant holding the maximum value an {@code int} can
  68      * have, 2<sup>31</sup>-1.
  69      */
  70     @Native public static final int   MAX_VALUE = 0x7fffffff;
  71 
  72     /**
  73      * The {@code Class} instance representing the primitive type
  74      * {@code int}.
  75      *
  76      * @since   1.1
  77      */
  78     @SuppressWarnings("unchecked")
  79     public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
  80 
  81     /**
  82      * All possible chars for representing a number as a String
  83      */
  84     static final char[] digits = {
  85         '0' , '1' , '2' , '3' , '4' , '5' ,
  86         '6' , '7' , '8' , '9' , 'a' , 'b' ,
  87         'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
  88         'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
  89         'o' , 'p' , 'q' , 'r' , 's' , 't' ,
  90         'u' , 'v' , 'w' , 'x' , 'y' , 'z'
  91     };
  92 
  93     /**
  94      * Returns a string representation of the first argument in the
  95      * radix specified by the second argument.
  96      *
  97      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
  98      * or larger than {@code Character.MAX_RADIX}, then the radix
  99      * {@code 10} is used instead.
 100      *
 101      * <p>If the first argument is negative, the first element of the
 102      * result is the ASCII minus character {@code '-'}
 103      * ({@code '\u005Cu002D'}). If the first argument is not
 104      * negative, no sign character appears in the result.
 105      *
 106      * <p>The remaining characters of the result represent the magnitude
 107      * of the first argument. If the magnitude is zero, it is
 108      * represented by a single zero character {@code '0'}
 109      * ({@code '\u005Cu0030'}); otherwise, the first character of
 110      * the representation of the magnitude will not be the zero
 111      * character.  The following ASCII characters are used as digits:
 112      *
 113      * <blockquote>
 114      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
 115      * </blockquote>
 116      *
 117      * These are {@code '\u005Cu0030'} through
 118      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 119      * {@code '\u005Cu007A'}. If {@code radix} is
 120      * <var>N</var>, then the first <var>N</var> of these characters
 121      * are used as radix-<var>N</var> digits in the order shown. Thus,
 122      * the digits for hexadecimal (radix 16) are
 123      * {@code 0123456789abcdef}. If uppercase letters are
 124      * desired, the {@link java.lang.String#toUpperCase()} method may
 125      * be called on the result:
 126      *
 127      * <blockquote>
 128      *  {@code Integer.toString(n, 16).toUpperCase()}
 129      * </blockquote>
 130      *
 131      * @param   i       an integer to be converted to a string.
 132      * @param   radix   the radix to use in the string representation.
 133      * @return  a string representation of the argument in the specified radix.
 134      * @see     java.lang.Character#MAX_RADIX
 135      * @see     java.lang.Character#MIN_RADIX
 136      */
 137     public static String toString(int i, int radix) {
 138         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 139             radix = 10;
 140 
 141         /* Use the faster version */
 142         if (radix == 10) {
 143             return toString(i);
 144         }
 145 
 146         if (COMPACT_STRINGS) {
 147             byte[] buf = new byte[33];
 148             boolean negative = (i < 0);
 149             int charPos = 32;
 150 
 151             if (!negative) {
 152                 i = -i;
 153             }
 154 
 155             while (i <= -radix) {
 156                 buf[charPos--] = (byte)digits[-(i % radix)];
 157                 i = i / radix;
 158             }
 159             buf[charPos] = (byte)digits[-i];
 160 
 161             if (negative) {
 162                 buf[--charPos] = '-';
 163             }
 164 
 165             return StringLatin1.newString(buf, charPos, (33 - charPos));
 166         }
 167         return toStringUTF16(i, radix);
 168     }
 169 
 170     private static String toStringUTF16(int i, int radix) {
 171         byte[] buf = new byte[33 * 2];
 172         boolean negative = (i < 0);
 173         int charPos = 32;
 174         if (!negative) {
 175             i = -i;
 176         }
 177         while (i <= -radix) {
 178             StringUTF16.putChar(buf, charPos--, digits[-(i % radix)]);
 179             i = i / radix;
 180         }
 181         StringUTF16.putChar(buf, charPos, digits[-i]);
 182 
 183         if (negative) {
 184             StringUTF16.putChar(buf, --charPos, '-');
 185         }
 186         return StringUTF16.newString(buf, charPos, (33 - charPos));
 187     }
 188 
 189     /**
 190      * Returns a string representation of the first argument as an
 191      * unsigned integer value in the radix specified by the second
 192      * argument.
 193      *
 194      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 195      * or larger than {@code Character.MAX_RADIX}, then the radix
 196      * {@code 10} is used instead.
 197      *
 198      * <p>Note that since the first argument is treated as an unsigned
 199      * value, no leading sign character is printed.
 200      *
 201      * <p>If the magnitude is zero, it is represented by a single zero
 202      * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
 203      * the first character of the representation of the magnitude will
 204      * not be the zero character.
 205      *
 206      * <p>The behavior of radixes and the characters used as digits
 207      * are the same as {@link #toString(int, int) toString}.
 208      *
 209      * @param   i       an integer to be converted to an unsigned string.
 210      * @param   radix   the radix to use in the string representation.
 211      * @return  an unsigned string representation of the argument in the specified radix.
 212      * @see     #toString(int, int)
 213      * @since 1.8
 214      */
 215     public static String toUnsignedString(int i, int radix) {
 216         return Long.toUnsignedString(toUnsignedLong(i), radix);
 217     }
 218 
 219     /**
 220      * Returns a string representation of the integer argument as an
 221      * unsigned integer in base&nbsp;16.
 222      *
 223      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 224      * if the argument is negative; otherwise, it is equal to the
 225      * argument.  This value is converted to a string of ASCII digits
 226      * in hexadecimal (base&nbsp;16) with no extra leading
 227      * {@code 0}s.
 228      *
 229      * <p>The value of the argument can be recovered from the returned
 230      * string {@code s} by calling {@link
 231      * Integer#parseUnsignedInt(String, int)
 232      * Integer.parseUnsignedInt(s, 16)}.
 233      *
 234      * <p>If the unsigned magnitude is zero, it is represented by a
 235      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 236      * otherwise, the first character of the representation of the
 237      * unsigned magnitude will not be the zero character. The
 238      * following characters are used as hexadecimal digits:
 239      *
 240      * <blockquote>
 241      *  {@code 0123456789abcdef}
 242      * </blockquote>
 243      *
 244      * These are the characters {@code '\u005Cu0030'} through
 245      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 246      * {@code '\u005Cu0066'}. If uppercase letters are
 247      * desired, the {@link java.lang.String#toUpperCase()} method may
 248      * be called on the result:
 249      *
 250      * <blockquote>
 251      *  {@code Integer.toHexString(n).toUpperCase()}
 252      * </blockquote>
 253      *
 254      * @param   i   an integer to be converted to a string.
 255      * @return  the string representation of the unsigned integer value
 256      *          represented by the argument in hexadecimal (base&nbsp;16).
 257      * @see #parseUnsignedInt(String, int)
 258      * @see #toUnsignedString(int, int)
 259      * @since   1.0.2
 260      */
 261     public static String toHexString(int i) {
 262         return toUnsignedString0(i, 4);
 263     }
 264 
 265     /**
 266      * Returns a string representation of the integer argument as an
 267      * unsigned integer in base&nbsp;8.
 268      *
 269      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 270      * if the argument is negative; otherwise, it is equal to the
 271      * argument.  This value is converted to a string of ASCII digits
 272      * in octal (base&nbsp;8) with no extra leading {@code 0}s.
 273      *
 274      * <p>The value of the argument can be recovered from the returned
 275      * string {@code s} by calling {@link
 276      * Integer#parseUnsignedInt(String, int)
 277      * Integer.parseUnsignedInt(s, 8)}.
 278      *
 279      * <p>If the unsigned magnitude is zero, it is represented by a
 280      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 281      * otherwise, the first character of the representation of the
 282      * unsigned magnitude will not be the zero character. The
 283      * following characters are used as octal digits:
 284      *
 285      * <blockquote>
 286      * {@code 01234567}
 287      * </blockquote>
 288      *
 289      * These are the characters {@code '\u005Cu0030'} through
 290      * {@code '\u005Cu0037'}.
 291      *
 292      * @param   i   an integer to be converted to a string.
 293      * @return  the string representation of the unsigned integer value
 294      *          represented by the argument in octal (base&nbsp;8).
 295      * @see #parseUnsignedInt(String, int)
 296      * @see #toUnsignedString(int, int)
 297      * @since   1.0.2
 298      */
 299     public static String toOctalString(int i) {
 300         return toUnsignedString0(i, 3);
 301     }
 302 
 303     /**
 304      * Returns a string representation of the integer argument as an
 305      * unsigned integer in base&nbsp;2.
 306      *
 307      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 308      * if the argument is negative; otherwise it is equal to the
 309      * argument.  This value is converted to a string of ASCII digits
 310      * in binary (base&nbsp;2) with no extra leading {@code 0}s.
 311      *
 312      * <p>The value of the argument can be recovered from the returned
 313      * string {@code s} by calling {@link
 314      * Integer#parseUnsignedInt(String, int)
 315      * Integer.parseUnsignedInt(s, 2)}.
 316      *
 317      * <p>If the unsigned magnitude is zero, it is represented by a
 318      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 319      * otherwise, the first character of the representation of the
 320      * unsigned magnitude will not be the zero character. The
 321      * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
 322      * '1'} ({@code '\u005Cu0031'}) are used as binary digits.
 323      *
 324      * @param   i   an integer to be converted to a string.
 325      * @return  the string representation of the unsigned integer value
 326      *          represented by the argument in binary (base&nbsp;2).
 327      * @see #parseUnsignedInt(String, int)
 328      * @see #toUnsignedString(int, int)
 329      * @since   1.0.2
 330      */
 331     public static String toBinaryString(int i) {
 332         return toUnsignedString0(i, 1);
 333     }
 334 
 335     /**
 336      * Convert the integer to an unsigned number.
 337      */
 338     private static String toUnsignedString0(int val, int shift) {
 339         // assert shift > 0 && shift <=5 : "Illegal shift value";
 340         int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
 341         int chars = Math.max(((mag + (shift - 1)) / shift), 1);
 342         if (COMPACT_STRINGS) {
 343             byte[] buf = new byte[chars];
 344             formatUnsignedInt(val, shift, buf, 0, chars);
 345             return new String(buf, LATIN1);
 346         } else {
 347             byte[] buf = new byte[chars * 2];
 348             formatUnsignedIntUTF16(val, shift, buf, 0, chars);
 349             return new String(buf, UTF16);
 350         }
 351     }
 352 
 353     /**
 354      * Format an {@code int} (treated as unsigned) into a character buffer. If
 355      * {@code len} exceeds the formatted ASCII representation of {@code val},
 356      * {@code buf} will be padded with leading zeroes.
 357      *
 358      * @param val the unsigned int to format
 359      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 360      * @param buf the character buffer to write to
 361      * @param offset the offset in the destination buffer to start at
 362      * @param len the number of characters to write
 363      */
 364     static void formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
 365         // assert shift > 0 && shift <=5 : "Illegal shift value";
 366         // assert offset >= 0 && offset < buf.length : "illegal offset";
 367         // assert len > 0 && (offset + len) <= buf.length : "illegal length";
 368         int charPos = offset + len;
 369         int radix = 1 << shift;
 370         int mask = radix - 1;
 371         do {
 372             buf[--charPos] = Integer.digits[val & mask];
 373             val >>>= shift;
 374         } while (charPos > offset);
 375     }
 376 
 377     /** byte[]/LATIN1 version    */
 378     static void formatUnsignedInt(int val, int shift, byte[] buf, int offset, int len) {
 379         int charPos = offset + len;
 380         int radix = 1 << shift;
 381         int mask = radix - 1;
 382         do {
 383             buf[--charPos] = (byte)Integer.digits[val & mask];
 384             val >>>= shift;
 385         } while (charPos > offset);
 386     }
 387 
 388     /** byte[]/UTF16 version    */
 389     static void formatUnsignedIntUTF16(int val, int shift, byte[] buf, int offset, int len) {
 390         int charPos = offset + len;
 391         int radix = 1 << shift;
 392         int mask = radix - 1;
 393         do {
 394             StringUTF16.putChar(buf, --charPos, Integer.digits[val & mask]);
 395             val >>>= shift;
 396         } while (charPos > offset);
 397     }
 398 
 399     static final byte[] DigitTens = {
 400         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
 401         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
 402         '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
 403         '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
 404         '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
 405         '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
 406         '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
 407         '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
 408         '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
 409         '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
 410         } ;
 411 
 412     static final byte[] DigitOnes = {
 413         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 414         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 415         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 416         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 417         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 418         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 419         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 420         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 421         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 422         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 423         } ;
 424 
 425 
 426     /**
 427      * Returns a {@code String} object representing the
 428      * specified integer. The argument is converted to signed decimal
 429      * representation and returned as a string, exactly as if the
 430      * argument and radix 10 were given as arguments to the {@link
 431      * #toString(int, int)} method.
 432      *
 433      * @param   i   an integer to be converted.
 434      * @return  a string representation of the argument in base&nbsp;10.
 435      */
 436     @HotSpotIntrinsicCandidate
 437     public static String toString(int i) {
 438         int size = stringSize(i);
 439         if (COMPACT_STRINGS) {
 440             byte[] buf = new byte[size];
 441             getChars(i, size, buf);
 442             return new String(buf, LATIN1);
 443         } else {
 444             byte[] buf = new byte[size * 2];
 445             getCharsUTF16(i, size, buf);
 446             return new String(buf, UTF16);
 447         }
 448     }
 449 
 450     /**
 451      * Returns a string representation of the argument as an unsigned
 452      * decimal value.
 453      *
 454      * The argument is converted to unsigned decimal representation
 455      * and returned as a string exactly as if the argument and radix
 456      * 10 were given as arguments to the {@link #toUnsignedString(int,
 457      * int)} method.
 458      *
 459      * @param   i  an integer to be converted to an unsigned string.
 460      * @return  an unsigned string representation of the argument.
 461      * @see     #toUnsignedString(int, int)
 462      * @since 1.8
 463      */
 464     public static String toUnsignedString(int i) {
 465         return Long.toString(toUnsignedLong(i));
 466     }
 467 
 468     /**
 469      * Places characters representing the integer i into the
 470      * character array buf. The characters are placed into
 471      * the buffer backwards starting with the least significant
 472      * digit at the specified index (exclusive), and working
 473      * backwards from there.
 474      *
 475      * @implNote This method converts positive inputs into negative
 476      * values, to cover the Integer.MIN_VALUE case. Converting otherwise
 477      * (negative to positive) will expose -Integer.MIN_VALUE that overflows
 478      * integer.
 479      *
 480      * @param i     value to convert
 481      * @param index next index, after the least significant digit
 482      * @param buf   target buffer, Latin1-encoded
 483      * @return index of the most significant digit or minus sign, if present
 484      */
 485     static int getChars(int i, int index, byte[] buf) {
 486         int q, r;
 487         int charPos = index;
 488 
 489         boolean negative = i < 0;
 490         if (!negative) {
 491             i = -i;
 492         }
 493 
 494         // Generate two digits per iteration
 495         while (i <= -100) {
 496             q = i / 100;
 497             r = (q * 100) - i;
 498             i = q;
 499             buf[--charPos] = DigitOnes[r];
 500             buf[--charPos] = DigitTens[r];
 501         }
 502 
 503         // We know there are at most two digits left at this point.
 504         q = i / 10;
 505         r = (q * 10) - i;
 506         buf[--charPos] = (byte)('0' + r);
 507 
 508         // Whatever left is the remaining digit.
 509         if (q < 0) {
 510             buf[--charPos] = (byte)('0' - q);
 511         }
 512 
 513         if (negative) {
 514             buf[--charPos] = (byte)'-';
 515         }
 516         return charPos;
 517     }
 518 
 519     /**
 520      * This is a variant of {@link #getChars(int, int, byte[])}, but for
 521      * UTF-16 coder.
 522      *
 523      * @param i     value to convert
 524      * @param index next index, after the least significant digit
 525      * @param buf   target buffer, UTF16-coded.
 526      * @return index of the most significant digit or minus sign, if present
 527      */
 528     static int getCharsUTF16(int i, int index, byte[] buf) {
 529         int q, r;
 530         int charPos = index;
 531 
 532         boolean negative = (i < 0);
 533         if (!negative) {
 534             i = -i;
 535         }
 536 
 537         // Get 2 digits/iteration using ints
 538         while (i <= -100) {
 539             q = i / 100;
 540             r = (q * 100) - i;
 541             i = q;
 542             StringUTF16.putChar(buf, --charPos, DigitOnes[r]);
 543             StringUTF16.putChar(buf, --charPos, DigitTens[r]);
 544         }
 545 
 546         // We know there are at most two digits left at this point.
 547         q = i / 10;
 548         r = (q * 10) - i;
 549         StringUTF16.putChar(buf, --charPos, '0' + r);
 550 
 551         // Whatever left is the remaining digit.
 552         if (q < 0) {
 553             StringUTF16.putChar(buf, --charPos, '0' - q);
 554         }
 555 
 556         if (negative) {
 557             StringUTF16.putChar(buf, --charPos, '-');
 558         }
 559         return charPos;
 560     }
 561 
 562     // Left here for compatibility reasons, see JDK-8143900.
 563     static final int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
 564                                       99999999, 999999999, Integer.MAX_VALUE };
 565 
 566     /**
 567      * Returns the string representation size for a given int value.
 568      *
 569      * @param x int value
 570      * @return string size
 571      *
 572      * @implNote There are other ways to compute this: e.g. binary search,
 573      * but values are biased heavily towards zero, and therefore linear search
 574      * wins. The iteration results are also routinely inlined in the generated
 575      * code after loop unrolling.
 576      */
 577     static int stringSize(int x) {
 578         int d = 1;
 579         if (x >= 0) {
 580             d = 0;
 581             x = -x;
 582         }
 583         int p = -10;
 584         for (int i = 1; i < 10; i++) {
 585             if (x > p)
 586                 return i + d;
 587             p = 10 * p;
 588         }
 589         return 10 + d;
 590     }
 591 
 592     /**
 593      * Parses the string argument as a signed integer in the radix
 594      * specified by the second argument. The characters in the string
 595      * must all be digits of the specified radix (as determined by
 596      * whether {@link java.lang.Character#digit(char, int)} returns a
 597      * nonnegative value), except that the first character may be an
 598      * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
 599      * indicate a negative value or an ASCII plus sign {@code '+'}
 600      * ({@code '\u005Cu002B'}) to indicate a positive value. The
 601      * resulting integer value is returned.
 602      *
 603      * <p>An exception of type {@code NumberFormatException} is
 604      * thrown if any of the following situations occurs:
 605      * <ul>
 606      * <li>The first argument is {@code null} or is a string of
 607      * length zero.
 608      *
 609      * <li>The radix is either smaller than
 610      * {@link java.lang.Character#MIN_RADIX} or
 611      * larger than {@link java.lang.Character#MAX_RADIX}.
 612      *
 613      * <li>Any character of the string is not a digit of the specified
 614      * radix, except that the first character may be a minus sign
 615      * {@code '-'} ({@code '\u005Cu002D'}) or plus sign
 616      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 617      * string is longer than length 1.
 618      *
 619      * <li>The value represented by the string is not a value of type
 620      * {@code int}.
 621      * </ul>
 622      *
 623      * <p>Examples:
 624      * <blockquote><pre>
 625      * parseInt("0", 10) returns 0
 626      * parseInt("473", 10) returns 473
 627      * parseInt("+42", 10) returns 42
 628      * parseInt("-0", 10) returns 0
 629      * parseInt("-FF", 16) returns -255
 630      * parseInt("1100110", 2) returns 102
 631      * parseInt("2147483647", 10) returns 2147483647
 632      * parseInt("-2147483648", 10) returns -2147483648
 633      * parseInt("2147483648", 10) throws a NumberFormatException
 634      * parseInt("99", 8) throws a NumberFormatException
 635      * parseInt("Kona", 10) throws a NumberFormatException
 636      * parseInt("Kona", 27) returns 411787
 637      * </pre></blockquote>
 638      *
 639      * @param      s   the {@code String} containing the integer
 640      *                  representation to be parsed
 641      * @param      radix   the radix to be used while parsing {@code s}.
 642      * @return     the integer represented by the string argument in the
 643      *             specified radix.
 644      * @exception  NumberFormatException if the {@code String}
 645      *             does not contain a parsable {@code int}.
 646      */
 647     public static int parseInt(String s, int radix)
 648                 throws NumberFormatException
 649     {
 650         /*
 651          * WARNING: This method may be invoked early during VM initialization
 652          * before IntegerCache is initialized. Care must be taken to not use
 653          * the valueOf method.
 654          */
 655 
 656         if (s == null) {
 657             throw new NumberFormatException("null");
 658         }
 659 
 660         if (radix < Character.MIN_RADIX) {
 661             throw new NumberFormatException("radix " + radix +
 662                                             " less than Character.MIN_RADIX");
 663         }
 664 
 665         if (radix > Character.MAX_RADIX) {
 666             throw new NumberFormatException("radix " + radix +
 667                                             " greater than Character.MAX_RADIX");
 668         }
 669 
 670         boolean negative = false;
 671         int i = 0, len = s.length();
 672         int limit = -Integer.MAX_VALUE;
 673 
 674         if (len > 0) {
 675             char firstChar = s.charAt(0);
 676             if (firstChar < '0') { // Possible leading "+" or "-"
 677                 if (firstChar == '-') {
 678                     negative = true;
 679                     limit = Integer.MIN_VALUE;
 680                 } else if (firstChar != '+') {
 681                     throw NumberFormatException.forInputString(s);
 682                 }
 683 
 684                 if (len == 1) { // Cannot have lone "+" or "-"
 685                     throw NumberFormatException.forInputString(s);
 686                 }
 687                 i++;
 688             }
 689             int multmin = limit / radix;
 690             int result = 0;
 691             while (i < len) {
 692                 // Accumulating negatively avoids surprises near MAX_VALUE
 693                 int digit = Character.digit(s.charAt(i++), radix);
 694                 if (digit < 0 || result < multmin) {
 695                     throw NumberFormatException.forInputString(s);
 696                 }
 697                 result *= radix;
 698                 if (result < limit + digit) {
 699                     throw NumberFormatException.forInputString(s);
 700                 }
 701                 result -= digit;
 702             }
 703             return negative ? result : -result;
 704         } else {
 705             throw NumberFormatException.forInputString(s);
 706         }
 707     }
 708 
 709     /**
 710      * Parses the {@link CharSequence} argument as a signed {@code int} in the
 711      * specified {@code radix}, beginning at the specified {@code beginIndex}
 712      * and extending to {@code endIndex - 1}.
 713      *
 714      * <p>The method does not take steps to guard against the
 715      * {@code CharSequence} being mutated while parsing.
 716      *
 717      * @param      s   the {@code CharSequence} containing the {@code int}
 718      *                  representation to be parsed
 719      * @param      beginIndex   the beginning index, inclusive.
 720      * @param      endIndex     the ending index, exclusive.
 721      * @param      radix   the radix to be used while parsing {@code s}.
 722      * @return     the signed {@code int} represented by the subsequence in
 723      *             the specified radix.
 724      * @throws     NullPointerException  if {@code s} is null.
 725      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 726      *             negative, or if {@code beginIndex} is greater than
 727      *             {@code endIndex} or if {@code endIndex} is greater than
 728      *             {@code s.length()}.
 729      * @throws     NumberFormatException  if the {@code CharSequence} does not
 730      *             contain a parsable {@code int} in the specified
 731      *             {@code radix}, or if {@code radix} is either smaller than
 732      *             {@link java.lang.Character#MIN_RADIX} or larger than
 733      *             {@link java.lang.Character#MAX_RADIX}.
 734      * @since  9
 735      */
 736     public static int parseInt(CharSequence s, int beginIndex, int endIndex, int radix)
 737                 throws NumberFormatException {
 738         s = Objects.requireNonNull(s);
 739 
 740         if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) {
 741             throw new IndexOutOfBoundsException();
 742         }
 743         if (radix < Character.MIN_RADIX) {
 744             throw new NumberFormatException("radix " + radix +
 745                                             " less than Character.MIN_RADIX");
 746         }
 747         if (radix > Character.MAX_RADIX) {
 748             throw new NumberFormatException("radix " + radix +
 749                                             " greater than Character.MAX_RADIX");
 750         }
 751 
 752         boolean negative = false;
 753         int i = beginIndex;
 754         int limit = -Integer.MAX_VALUE;
 755 
 756         if (i < endIndex) {
 757             char firstChar = s.charAt(i);
 758             if (firstChar < '0') { // Possible leading "+" or "-"
 759                 if (firstChar == '-') {
 760                     negative = true;
 761                     limit = Integer.MIN_VALUE;
 762                 } else if (firstChar != '+') {
 763                     throw NumberFormatException.forCharSequence(s, beginIndex,
 764                             endIndex, i);
 765                 }
 766                 i++;
 767                 if (i == endIndex) { // Cannot have lone "+" or "-"
 768                     throw NumberFormatException.forCharSequence(s, beginIndex,
 769                             endIndex, i);
 770                 }
 771             }
 772             int multmin = limit / radix;
 773             int result = 0;
 774             while (i < endIndex) {
 775                 // Accumulating negatively avoids surprises near MAX_VALUE
 776                 int digit = Character.digit(s.charAt(i), radix);
 777                 if (digit < 0 || result < multmin) {
 778                     throw NumberFormatException.forCharSequence(s, beginIndex,
 779                             endIndex, i);
 780                 }
 781                 result *= radix;
 782                 if (result < limit + digit) {
 783                     throw NumberFormatException.forCharSequence(s, beginIndex,
 784                             endIndex, i);
 785                 }
 786                 i++;
 787                 result -= digit;
 788             }
 789             return negative ? result : -result;
 790         } else {
 791             throw NumberFormatException.forInputString("");
 792         }
 793     }
 794 
 795     /**
 796      * Parses the string argument as a signed decimal integer. The
 797      * characters in the string must all be decimal digits, except
 798      * that the first character may be an ASCII minus sign {@code '-'}
 799      * ({@code '\u005Cu002D'}) to indicate a negative value or an
 800      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 801      * indicate a positive value. The resulting integer value is
 802      * returned, exactly as if the argument and the radix 10 were
 803      * given as arguments to the {@link #parseInt(java.lang.String,
 804      * int)} method.
 805      *
 806      * @param s    a {@code String} containing the {@code int}
 807      *             representation to be parsed
 808      * @return     the integer value represented by the argument in decimal.
 809      * @exception  NumberFormatException  if the string does not contain a
 810      *               parsable integer.
 811      */
 812     public static int parseInt(String s) throws NumberFormatException {
 813         return parseInt(s,10);
 814     }
 815 
 816     /**
 817      * Parses the string argument as an unsigned integer in the radix
 818      * specified by the second argument.  An unsigned integer maps the
 819      * values usually associated with negative numbers to positive
 820      * numbers larger than {@code MAX_VALUE}.
 821      *
 822      * The characters in the string must all be digits of the
 823      * specified radix (as determined by whether {@link
 824      * java.lang.Character#digit(char, int)} returns a nonnegative
 825      * value), except that the first character may be an ASCII plus
 826      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 827      * integer value is returned.
 828      *
 829      * <p>An exception of type {@code NumberFormatException} is
 830      * thrown if any of the following situations occurs:
 831      * <ul>
 832      * <li>The first argument is {@code null} or is a string of
 833      * length zero.
 834      *
 835      * <li>The radix is either smaller than
 836      * {@link java.lang.Character#MIN_RADIX} or
 837      * larger than {@link java.lang.Character#MAX_RADIX}.
 838      *
 839      * <li>Any character of the string is not a digit of the specified
 840      * radix, except that the first character may be a plus sign
 841      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 842      * string is longer than length 1.
 843      *
 844      * <li>The value represented by the string is larger than the
 845      * largest unsigned {@code int}, 2<sup>32</sup>-1.
 846      *
 847      * </ul>
 848      *
 849      *
 850      * @param      s   the {@code String} containing the unsigned integer
 851      *                  representation to be parsed
 852      * @param      radix   the radix to be used while parsing {@code s}.
 853      * @return     the integer represented by the string argument in the
 854      *             specified radix.
 855      * @throws     NumberFormatException if the {@code String}
 856      *             does not contain a parsable {@code int}.
 857      * @since 1.8
 858      */
 859     public static int parseUnsignedInt(String s, int radix)
 860                 throws NumberFormatException {
 861         if (s == null)  {
 862             throw new NumberFormatException("null");
 863         }
 864 
 865         int len = s.length();
 866         if (len > 0) {
 867             char firstChar = s.charAt(0);
 868             if (firstChar == '-') {
 869                 throw new
 870                     NumberFormatException(String.format("Illegal leading minus sign " +
 871                                                        "on unsigned string %s.", s));
 872             } else {
 873                 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
 874                     (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
 875                     return parseInt(s, radix);
 876                 } else {
 877                     long ell = Long.parseLong(s, radix);
 878                     if ((ell & 0xffff_ffff_0000_0000L) == 0) {
 879                         return (int) ell;
 880                     } else {
 881                         throw new
 882                             NumberFormatException(String.format("String value %s exceeds " +
 883                                                                 "range of unsigned int.", s));
 884                     }
 885                 }
 886             }
 887         } else {
 888             throw NumberFormatException.forInputString(s);
 889         }
 890     }
 891 
 892     /**
 893      * Parses the {@link CharSequence} argument as an unsigned {@code int} in
 894      * the specified {@code radix}, beginning at the specified
 895      * {@code beginIndex} and extending to {@code endIndex - 1}.
 896      *
 897      * <p>The method does not take steps to guard against the
 898      * {@code CharSequence} being mutated while parsing.
 899      *
 900      * @param      s   the {@code CharSequence} containing the unsigned
 901      *                 {@code int} representation to be parsed
 902      * @param      beginIndex   the beginning index, inclusive.
 903      * @param      endIndex     the ending index, exclusive.
 904      * @param      radix   the radix to be used while parsing {@code s}.
 905      * @return     the unsigned {@code int} represented by the subsequence in
 906      *             the specified radix.
 907      * @throws     NullPointerException  if {@code s} is null.
 908      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 909      *             negative, or if {@code beginIndex} is greater than
 910      *             {@code endIndex} or if {@code endIndex} is greater than
 911      *             {@code s.length()}.
 912      * @throws     NumberFormatException  if the {@code CharSequence} does not
 913      *             contain a parsable unsigned {@code int} in the specified
 914      *             {@code radix}, or if {@code radix} is either smaller than
 915      *             {@link java.lang.Character#MIN_RADIX} or larger than
 916      *             {@link java.lang.Character#MAX_RADIX}.
 917      * @since  9
 918      */
 919     public static int parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix)
 920                 throws NumberFormatException {
 921         s = Objects.requireNonNull(s);
 922 
 923         if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) {
 924             throw new IndexOutOfBoundsException();
 925         }
 926         int start = beginIndex, len = endIndex - beginIndex;
 927 
 928         if (len > 0) {
 929             char firstChar = s.charAt(start);
 930             if (firstChar == '-') {
 931                 throw new
 932                     NumberFormatException(String.format("Illegal leading minus sign " +
 933                                                        "on unsigned string %s.", s));
 934             } else {
 935                 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
 936                         (radix == 10 && len <= 9)) { // Integer.MAX_VALUE in base 10 is 10 digits
 937                     return parseInt(s, start, start + len, radix);
 938                 } else {
 939                     long ell = Long.parseLong(s, start, start + len, radix);
 940                     if ((ell & 0xffff_ffff_0000_0000L) == 0) {
 941                         return (int) ell;
 942                     } else {
 943                         throw new
 944                             NumberFormatException(String.format("String value %s exceeds " +
 945                                                                 "range of unsigned int.", s));
 946                     }
 947                 }
 948             }
 949         } else {
 950             throw new NumberFormatException("");
 951         }
 952     }
 953 
 954     /**
 955      * Parses the string argument as an unsigned decimal integer. The
 956      * characters in the string must all be decimal digits, except
 957      * that the first character may be an ASCII plus sign {@code
 958      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 959      * is returned, exactly as if the argument and the radix 10 were
 960      * given as arguments to the {@link
 961      * #parseUnsignedInt(java.lang.String, int)} method.
 962      *
 963      * @param s   a {@code String} containing the unsigned {@code int}
 964      *            representation to be parsed
 965      * @return    the unsigned integer value represented by the argument in decimal.
 966      * @throws    NumberFormatException  if the string does not contain a
 967      *            parsable unsigned integer.
 968      * @since 1.8
 969      */
 970     public static int parseUnsignedInt(String s) throws NumberFormatException {
 971         return parseUnsignedInt(s, 10);
 972     }
 973 
 974     /**
 975      * Returns an {@code Integer} object holding the value
 976      * extracted from the specified {@code String} when parsed
 977      * with the radix given by the second argument. The first argument
 978      * is interpreted as representing a signed integer in the radix
 979      * specified by the second argument, exactly as if the arguments
 980      * were given to the {@link #parseInt(java.lang.String, int)}
 981      * method. The result is an {@code Integer} object that
 982      * represents the integer value specified by the string.
 983      *
 984      * <p>In other words, this method returns an {@code Integer}
 985      * object equal to the value of:
 986      *
 987      * <blockquote>
 988      *  {@code new Integer(Integer.parseInt(s, radix))}
 989      * </blockquote>
 990      *
 991      * @param      s   the string to be parsed.
 992      * @param      radix the radix to be used in interpreting {@code s}
 993      * @return     an {@code Integer} object holding the value
 994      *             represented by the string argument in the specified
 995      *             radix.
 996      * @exception NumberFormatException if the {@code String}
 997      *            does not contain a parsable {@code int}.
 998      */
 999     public static Integer valueOf(String s, int radix) throws NumberFormatException {
1000         return Integer.valueOf(parseInt(s,radix));
1001     }
1002 
1003     /**
1004      * Returns an {@code Integer} object holding the
1005      * value of the specified {@code String}. The argument is
1006      * interpreted as representing a signed decimal integer, exactly
1007      * as if the argument were given to the {@link
1008      * #parseInt(java.lang.String)} method. The result is an
1009      * {@code Integer} object that represents the integer value
1010      * specified by the string.
1011      *
1012      * <p>In other words, this method returns an {@code Integer}
1013      * object equal to the value of:
1014      *
1015      * <blockquote>
1016      *  {@code new Integer(Integer.parseInt(s))}
1017      * </blockquote>
1018      *
1019      * @param      s   the string to be parsed.
1020      * @return     an {@code Integer} object holding the value
1021      *             represented by the string argument.
1022      * @exception  NumberFormatException  if the string cannot be parsed
1023      *             as an integer.
1024      */
1025     public static Integer valueOf(String s) throws NumberFormatException {
1026         return Integer.valueOf(parseInt(s, 10));
1027     }
1028 
1029     /**
1030      * Cache to support the object identity semantics of autoboxing for values between
1031      * -128 and 127 (inclusive) as required by JLS.
1032      *
1033      * The cache is initialized on first usage.  The size of the cache
1034      * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
1035      * During VM initialization, java.lang.Integer.IntegerCache.high property
1036      * may be set and saved in the private system properties in the
1037      * jdk.internal.misc.VM class.
1038      */
1039 
1040     private static class IntegerCache {
1041         static final int low = -128;
1042         static final int high;
1043         static final Integer cache[];
1044 
1045         static {
1046             // high value may be configured by property
1047             int h = 127;
1048             String integerCacheHighPropValue =
1049                 VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
1050             if (integerCacheHighPropValue != null) {
1051                 try {
1052                     int i = parseInt(integerCacheHighPropValue);
1053                     i = Math.max(i, 127);
1054                     // Maximum array size is Integer.MAX_VALUE
1055                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
1056                 } catch( NumberFormatException nfe) {
1057                     // If the property cannot be parsed into an int, ignore it.
1058                 }
1059             }
1060             high = h;
1061 
1062             cache = new Integer[(high - low) + 1];
1063             int j = low;
1064             for(int k = 0; k < cache.length; k++)
1065                 cache[k] = new Integer(j++);
1066 
1067             // range [-128, 127] must be interned (JLS7 5.1.7)
1068             assert IntegerCache.high >= 127;
1069         }
1070 
1071         private IntegerCache() {}
1072     }
1073 
1074     /**
1075      * Returns an {@code Integer} instance representing the specified
1076      * {@code int} value.  If a new {@code Integer} instance is not
1077      * required, this method should generally be used in preference to
1078      * the constructor {@link #Integer(int)}, as this method is likely
1079      * to yield significantly better space and time performance by
1080      * caching frequently requested values.
1081      *
1082      * This method will always cache values in the range -128 to 127,
1083      * inclusive, and may cache other values outside of this range.
1084      *
1085      * @param  i an {@code int} value.
1086      * @return an {@code Integer} instance representing {@code i}.
1087      * @since  1.5
1088      */
1089     @HotSpotIntrinsicCandidate
1090     public static Integer valueOf(int i) {
1091         if (i >= IntegerCache.low && i <= IntegerCache.high)
1092             return IntegerCache.cache[i + (-IntegerCache.low)];
1093         return new Integer(i);
1094     }
1095 
1096     /**
1097      * The value of the {@code Integer}.
1098      *
1099      * @serial
1100      */
1101     private final int value;
1102 
1103     /**
1104      * Constructs a newly allocated {@code Integer} object that
1105      * represents the specified {@code int} value.
1106      *
1107      * @param   value   the value to be represented by the
1108      *                  {@code Integer} object.
1109      *
1110      * @deprecated
1111      * It is rarely appropriate to use this constructor. The static factory
1112      * {@link #valueOf(int)} is generally a better choice, as it is
1113      * likely to yield significantly better space and time performance.
1114      */
1115     @Deprecated(since="9")
1116     public Integer(int value) {
1117         this.value = value;
1118     }
1119 
1120     /**
1121      * Constructs a newly allocated {@code Integer} object that
1122      * represents the {@code int} value indicated by the
1123      * {@code String} parameter. The string is converted to an
1124      * {@code int} value in exactly the manner used by the
1125      * {@code parseInt} method for radix 10.
1126      *
1127      * @param   s   the {@code String} to be converted to an {@code Integer}.
1128      * @throws      NumberFormatException if the {@code String} does not
1129      *              contain a parsable integer.
1130      *
1131      * @deprecated
1132      * It is rarely appropriate to use this constructor.
1133      * Use {@link #parseInt(String)} to convert a string to a
1134      * {@code int} primitive, or use {@link #valueOf(String)}
1135      * to convert a string to an {@code Integer} object.
1136      */
1137     @Deprecated(since="9")
1138     public Integer(String s) throws NumberFormatException {
1139         this.value = parseInt(s, 10);
1140     }
1141 
1142     /**
1143      * Returns the value of this {@code Integer} as a {@code byte}
1144      * after a narrowing primitive conversion.
1145      * @jls 5.1.3 Narrowing Primitive Conversions
1146      */
1147     public byte byteValue() {
1148         return (byte)value;
1149     }
1150 
1151     /**
1152      * Returns the value of this {@code Integer} as a {@code short}
1153      * after a narrowing primitive conversion.
1154      * @jls 5.1.3 Narrowing Primitive Conversions
1155      */
1156     public short shortValue() {
1157         return (short)value;
1158     }
1159 
1160     /**
1161      * Returns the value of this {@code Integer} as an
1162      * {@code int}.
1163      */
1164     @HotSpotIntrinsicCandidate
1165     public int intValue() {
1166         return value;
1167     }
1168 
1169     /**
1170      * Returns the value of this {@code Integer} as a {@code long}
1171      * after a widening primitive conversion.
1172      * @jls 5.1.2 Widening Primitive Conversions
1173      * @see Integer#toUnsignedLong(int)
1174      */
1175     public long longValue() {
1176         return (long)value;
1177     }
1178 
1179     /**
1180      * Returns the value of this {@code Integer} as a {@code float}
1181      * after a widening primitive conversion.
1182      * @jls 5.1.2 Widening Primitive Conversions
1183      */
1184     public float floatValue() {
1185         return (float)value;
1186     }
1187 
1188     /**
1189      * Returns the value of this {@code Integer} as a {@code double}
1190      * after a widening primitive conversion.
1191      * @jls 5.1.2 Widening Primitive Conversions
1192      */
1193     public double doubleValue() {
1194         return (double)value;
1195     }
1196 
1197     /**
1198      * Returns a {@code String} object representing this
1199      * {@code Integer}'s value. The value is converted to signed
1200      * decimal representation and returned as a string, exactly as if
1201      * the integer value were given as an argument to the {@link
1202      * java.lang.Integer#toString(int)} method.
1203      *
1204      * @return  a string representation of the value of this object in
1205      *          base&nbsp;10.
1206      */
1207     public String toString() {
1208         return toString(value);
1209     }
1210 
1211     /**
1212      * Returns a hash code for this {@code Integer}.
1213      *
1214      * @return  a hash code value for this object, equal to the
1215      *          primitive {@code int} value represented by this
1216      *          {@code Integer} object.
1217      */
1218     @Override
1219     public int hashCode() {
1220         return Integer.hashCode(value);
1221     }
1222 
1223     /**
1224      * Returns a hash code for an {@code int} value; compatible with
1225      * {@code Integer.hashCode()}.
1226      *
1227      * @param value the value to hash
1228      * @since 1.8
1229      *
1230      * @return a hash code value for an {@code int} value.
1231      */
1232     public static int hashCode(int value) {
1233         return value;
1234     }
1235 
1236     /**
1237      * Compares this object to the specified object.  The result is
1238      * {@code true} if and only if the argument is not
1239      * {@code null} and is an {@code Integer} object that
1240      * contains the same {@code int} value as this object.
1241      *
1242      * @param   obj   the object to compare with.
1243      * @return  {@code true} if the objects are the same;
1244      *          {@code false} otherwise.
1245      */
1246     public boolean equals(Object obj) {
1247         if (obj instanceof Integer) {
1248             return value == ((Integer)obj).intValue();
1249         }
1250         return false;
1251     }
1252 
1253     /**
1254      * Determines the integer value of the system property with the
1255      * specified name.
1256      *
1257      * <p>The first argument is treated as the name of a system
1258      * property.  System properties are accessible through the {@link
1259      * java.lang.System#getProperty(java.lang.String)} method. The
1260      * string value of this property is then interpreted as an integer
1261      * value using the grammar supported by {@link Integer#decode decode} and
1262      * an {@code Integer} object representing this value is returned.
1263      *
1264      * <p>If there is no property with the specified name, if the
1265      * specified name is empty or {@code null}, or if the property
1266      * does not have the correct numeric format, then {@code null} is
1267      * returned.
1268      *
1269      * <p>In other words, this method returns an {@code Integer}
1270      * object equal to the value of:
1271      *
1272      * <blockquote>
1273      *  {@code getInteger(nm, null)}
1274      * </blockquote>
1275      *
1276      * @param   nm   property name.
1277      * @return  the {@code Integer} value of the property.
1278      * @throws  SecurityException for the same reasons as
1279      *          {@link System#getProperty(String) System.getProperty}
1280      * @see     java.lang.System#getProperty(java.lang.String)
1281      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1282      */
1283     public static Integer getInteger(String nm) {
1284         return getInteger(nm, null);
1285     }
1286 
1287     /**
1288      * Determines the integer value of the system property with the
1289      * specified name.
1290      *
1291      * <p>The first argument is treated as the name of a system
1292      * property.  System properties are accessible through the {@link
1293      * java.lang.System#getProperty(java.lang.String)} method. The
1294      * string value of this property is then interpreted as an integer
1295      * value using the grammar supported by {@link Integer#decode decode} and
1296      * an {@code Integer} object representing this value is returned.
1297      *
1298      * <p>The second argument is the default value. An {@code Integer} object
1299      * that represents the value of the second argument is returned if there
1300      * is no property of the specified name, if the property does not have
1301      * the correct numeric format, or if the specified name is empty or
1302      * {@code null}.
1303      *
1304      * <p>In other words, this method returns an {@code Integer} object
1305      * equal to the value of:
1306      *
1307      * <blockquote>
1308      *  {@code getInteger(nm, new Integer(val))}
1309      * </blockquote>
1310      *
1311      * but in practice it may be implemented in a manner such as:
1312      *
1313      * <blockquote><pre>
1314      * Integer result = getInteger(nm, null);
1315      * return (result == null) ? new Integer(val) : result;
1316      * </pre></blockquote>
1317      *
1318      * to avoid the unnecessary allocation of an {@code Integer}
1319      * object when the default value is not needed.
1320      *
1321      * @param   nm   property name.
1322      * @param   val   default value.
1323      * @return  the {@code Integer} value of the property.
1324      * @throws  SecurityException for the same reasons as
1325      *          {@link System#getProperty(String) System.getProperty}
1326      * @see     java.lang.System#getProperty(java.lang.String)
1327      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1328      */
1329     public static Integer getInteger(String nm, int val) {
1330         Integer result = getInteger(nm, null);
1331         return (result == null) ? Integer.valueOf(val) : result;
1332     }
1333 
1334     /**
1335      * Returns the integer value of the system property with the
1336      * specified name.  The first argument is treated as the name of a
1337      * system property.  System properties are accessible through the
1338      * {@link java.lang.System#getProperty(java.lang.String)} method.
1339      * The string value of this property is then interpreted as an
1340      * integer value, as per the {@link Integer#decode decode} method,
1341      * and an {@code Integer} object representing this value is
1342      * returned; in summary:
1343      *
1344      * <ul><li>If the property value begins with the two ASCII characters
1345      *         {@code 0x} or the ASCII character {@code #}, not
1346      *      followed by a minus sign, then the rest of it is parsed as a
1347      *      hexadecimal integer exactly as by the method
1348      *      {@link #valueOf(java.lang.String, int)} with radix 16.
1349      * <li>If the property value begins with the ASCII character
1350      *     {@code 0} followed by another character, it is parsed as an
1351      *     octal integer exactly as by the method
1352      *     {@link #valueOf(java.lang.String, int)} with radix 8.
1353      * <li>Otherwise, the property value is parsed as a decimal integer
1354      * exactly as by the method {@link #valueOf(java.lang.String, int)}
1355      * with radix 10.
1356      * </ul>
1357      *
1358      * <p>The second argument is the default value. The default value is
1359      * returned if there is no property of the specified name, if the
1360      * property does not have the correct numeric format, or if the
1361      * specified name is empty or {@code null}.
1362      *
1363      * @param   nm   property name.
1364      * @param   val   default value.
1365      * @return  the {@code Integer} value of the property.
1366      * @throws  SecurityException for the same reasons as
1367      *          {@link System#getProperty(String) System.getProperty}
1368      * @see     System#getProperty(java.lang.String)
1369      * @see     System#getProperty(java.lang.String, java.lang.String)
1370      */
1371     public static Integer getInteger(String nm, Integer val) {
1372         String v = null;
1373         try {
1374             v = System.getProperty(nm);
1375         } catch (IllegalArgumentException | NullPointerException e) {
1376         }
1377         if (v != null) {
1378             try {
1379                 return Integer.decode(v);
1380             } catch (NumberFormatException e) {
1381             }
1382         }
1383         return val;
1384     }
1385 
1386     /**
1387      * Decodes a {@code String} into an {@code Integer}.
1388      * Accepts decimal, hexadecimal, and octal numbers given
1389      * by the following grammar:
1390      *
1391      * <blockquote>
1392      * <dl>
1393      * <dt><i>DecodableString:</i>
1394      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1395      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1396      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1397      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1398      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1399      *
1400      * <dt><i>Sign:</i>
1401      * <dd>{@code -}
1402      * <dd>{@code +}
1403      * </dl>
1404      * </blockquote>
1405      *
1406      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1407      * are as defined in section 3.10.1 of
1408      * <cite>The Java&trade; Language Specification</cite>,
1409      * except that underscores are not accepted between digits.
1410      *
1411      * <p>The sequence of characters following an optional
1412      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1413      * "{@code #}", or leading zero) is parsed as by the {@code
1414      * Integer.parseInt} method with the indicated radix (10, 16, or
1415      * 8).  This sequence of characters must represent a positive
1416      * value or a {@link NumberFormatException} will be thrown.  The
1417      * result is negated if first character of the specified {@code
1418      * String} is the minus sign.  No whitespace characters are
1419      * permitted in the {@code String}.
1420      *
1421      * @param     nm the {@code String} to decode.
1422      * @return    an {@code Integer} object holding the {@code int}
1423      *             value represented by {@code nm}
1424      * @exception NumberFormatException  if the {@code String} does not
1425      *            contain a parsable integer.
1426      * @see java.lang.Integer#parseInt(java.lang.String, int)
1427      */
1428     public static Integer decode(String nm) throws NumberFormatException {
1429         int radix = 10;
1430         int index = 0;
1431         boolean negative = false;
1432         Integer result;
1433 
1434         if (nm.length() == 0)
1435             throw new NumberFormatException("Zero length string");
1436         char firstChar = nm.charAt(0);
1437         // Handle sign, if present
1438         if (firstChar == '-') {
1439             negative = true;
1440             index++;
1441         } else if (firstChar == '+')
1442             index++;
1443 
1444         // Handle radix specifier, if present
1445         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1446             index += 2;
1447             radix = 16;
1448         }
1449         else if (nm.startsWith("#", index)) {
1450             index ++;
1451             radix = 16;
1452         }
1453         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1454             index ++;
1455             radix = 8;
1456         }
1457 
1458         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1459             throw new NumberFormatException("Sign character in wrong position");
1460 
1461         try {
1462             result = Integer.valueOf(nm.substring(index), radix);
1463             result = negative ? Integer.valueOf(-result.intValue()) : result;
1464         } catch (NumberFormatException e) {
1465             // If number is Integer.MIN_VALUE, we'll end up here. The next line
1466             // handles this case, and causes any genuine format error to be
1467             // rethrown.
1468             String constant = negative ? ("-" + nm.substring(index))
1469                                        : nm.substring(index);
1470             result = Integer.valueOf(constant, radix);
1471         }
1472         return result;
1473     }
1474 
1475     /**
1476      * Compares two {@code Integer} objects numerically.
1477      *
1478      * @param   anotherInteger   the {@code Integer} to be compared.
1479      * @return  the value {@code 0} if this {@code Integer} is
1480      *          equal to the argument {@code Integer}; a value less than
1481      *          {@code 0} if this {@code Integer} is numerically less
1482      *          than the argument {@code Integer}; and a value greater
1483      *          than {@code 0} if this {@code Integer} is numerically
1484      *           greater than the argument {@code Integer} (signed
1485      *           comparison).
1486      * @since   1.2
1487      */
1488     public int compareTo(Integer anotherInteger) {
1489         return compare(this.value, anotherInteger.value);
1490     }
1491 
1492     /**
1493      * Compares two {@code int} values numerically.
1494      * The value returned is identical to what would be returned by:
1495      * <pre>
1496      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
1497      * </pre>
1498      *
1499      * @param  x the first {@code int} to compare
1500      * @param  y the second {@code int} to compare
1501      * @return the value {@code 0} if {@code x == y};
1502      *         a value less than {@code 0} if {@code x < y}; and
1503      *         a value greater than {@code 0} if {@code x > y}
1504      * @since 1.7
1505      */
1506     public static int compare(int x, int y) {
1507         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1508     }
1509 
1510     /**
1511      * Compares two {@code int} values numerically treating the values
1512      * as unsigned.
1513      *
1514      * @param  x the first {@code int} to compare
1515      * @param  y the second {@code int} to compare
1516      * @return the value {@code 0} if {@code x == y}; a value less
1517      *         than {@code 0} if {@code x < y} as unsigned values; and
1518      *         a value greater than {@code 0} if {@code x > y} as
1519      *         unsigned values
1520      * @since 1.8
1521      */
1522     public static int compareUnsigned(int x, int y) {
1523         return compare(x + MIN_VALUE, y + MIN_VALUE);
1524     }
1525 
1526     /**
1527      * Converts the argument to a {@code long} by an unsigned
1528      * conversion.  In an unsigned conversion to a {@code long}, the
1529      * high-order 32 bits of the {@code long} are zero and the
1530      * low-order 32 bits are equal to the bits of the integer
1531      * argument.
1532      *
1533      * Consequently, zero and positive {@code int} values are mapped
1534      * to a numerically equal {@code long} value and negative {@code
1535      * int} values are mapped to a {@code long} value equal to the
1536      * input plus 2<sup>32</sup>.
1537      *
1538      * @param  x the value to convert to an unsigned {@code long}
1539      * @return the argument converted to {@code long} by an unsigned
1540      *         conversion
1541      * @since 1.8
1542      */
1543     public static long toUnsignedLong(int x) {
1544         return ((long) x) & 0xffffffffL;
1545     }
1546 
1547     /**
1548      * Returns the unsigned quotient of dividing the first argument by
1549      * the second where each argument and the result is interpreted as
1550      * an unsigned value.
1551      *
1552      * <p>Note that in two's complement arithmetic, the three other
1553      * basic arithmetic operations of add, subtract, and multiply are
1554      * bit-wise identical if the two operands are regarded as both
1555      * being signed or both being unsigned.  Therefore separate {@code
1556      * addUnsigned}, etc. methods are not provided.
1557      *
1558      * @param dividend the value to be divided
1559      * @param divisor the value doing the dividing
1560      * @return the unsigned quotient of the first argument divided by
1561      * the second argument
1562      * @see #remainderUnsigned
1563      * @since 1.8
1564      */
1565     public static int divideUnsigned(int dividend, int divisor) {
1566         // In lieu of tricky code, for now just use long arithmetic.
1567         return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
1568     }
1569 
1570     /**
1571      * Returns the unsigned remainder from dividing the first argument
1572      * by the second where each argument and the result is interpreted
1573      * as an unsigned value.
1574      *
1575      * @param dividend the value to be divided
1576      * @param divisor the value doing the dividing
1577      * @return the unsigned remainder of the first argument divided by
1578      * the second argument
1579      * @see #divideUnsigned
1580      * @since 1.8
1581      */
1582     public static int remainderUnsigned(int dividend, int divisor) {
1583         // In lieu of tricky code, for now just use long arithmetic.
1584         return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
1585     }
1586 
1587 
1588     // Bit twiddling
1589 
1590     /**
1591      * The number of bits used to represent an {@code int} value in two's
1592      * complement binary form.
1593      *
1594      * @since 1.5
1595      */
1596     @Native public static final int SIZE = 32;
1597 
1598     /**
1599      * The number of bytes used to represent an {@code int} value in two's
1600      * complement binary form.
1601      *
1602      * @since 1.8
1603      */
1604     public static final int BYTES = SIZE / Byte.SIZE;
1605 
1606     /**
1607      * Returns an {@code int} value with at most a single one-bit, in the
1608      * position of the highest-order ("leftmost") one-bit in the specified
1609      * {@code int} value.  Returns zero if the specified value has no
1610      * one-bits in its two's complement binary representation, that is, if it
1611      * is equal to zero.
1612      *
1613      * @param i the value whose highest one bit is to be computed
1614      * @return an {@code int} value with a single one-bit, in the position
1615      *     of the highest-order one-bit in the specified value, or zero if
1616      *     the specified value is itself equal to zero.
1617      * @since 1.5
1618      */
1619     public static int highestOneBit(int i) {
1620         // HD, Figure 3-1
1621         i |= (i >>  1);
1622         i |= (i >>  2);
1623         i |= (i >>  4);
1624         i |= (i >>  8);
1625         i |= (i >> 16);
1626         return i - (i >>> 1);
1627     }
1628 
1629     /**
1630      * Returns an {@code int} value with at most a single one-bit, in the
1631      * position of the lowest-order ("rightmost") one-bit in the specified
1632      * {@code int} value.  Returns zero if the specified value has no
1633      * one-bits in its two's complement binary representation, that is, if it
1634      * is equal to zero.
1635      *
1636      * @param i the value whose lowest one bit is to be computed
1637      * @return an {@code int} value with a single one-bit, in the position
1638      *     of the lowest-order one-bit in the specified value, or zero if
1639      *     the specified value is itself equal to zero.
1640      * @since 1.5
1641      */
1642     public static int lowestOneBit(int i) {
1643         // HD, Section 2-1
1644         return i & -i;
1645     }
1646 
1647     /**
1648      * Returns the number of zero bits preceding the highest-order
1649      * ("leftmost") one-bit in the two's complement binary representation
1650      * of the specified {@code int} value.  Returns 32 if the
1651      * specified value has no one-bits in its two's complement representation,
1652      * in other words if it is equal to zero.
1653      *
1654      * <p>Note that this method is closely related to the logarithm base 2.
1655      * For all positive {@code int} values x:
1656      * <ul>
1657      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1658      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1659      * </ul>
1660      *
1661      * @param i the value whose number of leading zeros is to be computed
1662      * @return the number of zero bits preceding the highest-order
1663      *     ("leftmost") one-bit in the two's complement binary representation
1664      *     of the specified {@code int} value, or 32 if the value
1665      *     is equal to zero.
1666      * @since 1.5
1667      */
1668     @HotSpotIntrinsicCandidate
1669     public static int numberOfLeadingZeros(int i) {
1670         // HD, Figure 5-6
1671         if (i == 0)
1672             return 32;
1673         int n = 1;
1674         if (i >>> 16 == 0) { n += 16; i <<= 16; }
1675         if (i >>> 24 == 0) { n +=  8; i <<=  8; }
1676         if (i >>> 28 == 0) { n +=  4; i <<=  4; }
1677         if (i >>> 30 == 0) { n +=  2; i <<=  2; }
1678         n -= i >>> 31;
1679         return n;
1680     }
1681 
1682     /**
1683      * Returns the number of zero bits following the lowest-order ("rightmost")
1684      * one-bit in the two's complement binary representation of the specified
1685      * {@code int} value.  Returns 32 if the specified value has no
1686      * one-bits in its two's complement representation, in other words if it is
1687      * equal to zero.
1688      *
1689      * @param i the value whose number of trailing zeros is to be computed
1690      * @return the number of zero bits following the lowest-order ("rightmost")
1691      *     one-bit in the two's complement binary representation of the
1692      *     specified {@code int} value, or 32 if the value is equal
1693      *     to zero.
1694      * @since 1.5
1695      */
1696     @HotSpotIntrinsicCandidate
1697     public static int numberOfTrailingZeros(int i) {
1698         // HD, Figure 5-14
1699         int y;
1700         if (i == 0) return 32;
1701         int n = 31;
1702         y = i <<16; if (y != 0) { n = n -16; i = y; }
1703         y = i << 8; if (y != 0) { n = n - 8; i = y; }
1704         y = i << 4; if (y != 0) { n = n - 4; i = y; }
1705         y = i << 2; if (y != 0) { n = n - 2; i = y; }
1706         return n - ((i << 1) >>> 31);
1707     }
1708 
1709     /**
1710      * Returns the number of one-bits in the two's complement binary
1711      * representation of the specified {@code int} value.  This function is
1712      * sometimes referred to as the <i>population count</i>.
1713      *
1714      * @param i the value whose bits are to be counted
1715      * @return the number of one-bits in the two's complement binary
1716      *     representation of the specified {@code int} value.
1717      * @since 1.5
1718      */
1719     @HotSpotIntrinsicCandidate
1720     public static int bitCount(int i) {
1721         // HD, Figure 5-2
1722         i = i - ((i >>> 1) & 0x55555555);
1723         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1724         i = (i + (i >>> 4)) & 0x0f0f0f0f;
1725         i = i + (i >>> 8);
1726         i = i + (i >>> 16);
1727         return i & 0x3f;
1728     }
1729 
1730     /**
1731      * Returns the value obtained by rotating the two's complement binary
1732      * representation of the specified {@code int} value left by the
1733      * specified number of bits.  (Bits shifted out of the left hand, or
1734      * high-order, side reenter on the right, or low-order.)
1735      *
1736      * <p>Note that left rotation with a negative distance is equivalent to
1737      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1738      * distance)}.  Note also that rotation by any multiple of 32 is a
1739      * no-op, so all but the last five bits of the rotation distance can be
1740      * ignored, even if the distance is negative: {@code rotateLeft(val,
1741      * distance) == rotateLeft(val, distance & 0x1F)}.
1742      *
1743      * @param i the value whose bits are to be rotated left
1744      * @param distance the number of bit positions to rotate left
1745      * @return the value obtained by rotating the two's complement binary
1746      *     representation of the specified {@code int} value left by the
1747      *     specified number of bits.
1748      * @since 1.5
1749      */
1750     public static int rotateLeft(int i, int distance) {
1751         return (i << distance) | (i >>> -distance);
1752     }
1753 
1754     /**
1755      * Returns the value obtained by rotating the two's complement binary
1756      * representation of the specified {@code int} value right by the
1757      * specified number of bits.  (Bits shifted out of the right hand, or
1758      * low-order, side reenter on the left, or high-order.)
1759      *
1760      * <p>Note that right rotation with a negative distance is equivalent to
1761      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1762      * distance)}.  Note also that rotation by any multiple of 32 is a
1763      * no-op, so all but the last five bits of the rotation distance can be
1764      * ignored, even if the distance is negative: {@code rotateRight(val,
1765      * distance) == rotateRight(val, distance & 0x1F)}.
1766      *
1767      * @param i the value whose bits are to be rotated right
1768      * @param distance the number of bit positions to rotate right
1769      * @return the value obtained by rotating the two's complement binary
1770      *     representation of the specified {@code int} value right by the
1771      *     specified number of bits.
1772      * @since 1.5
1773      */
1774     public static int rotateRight(int i, int distance) {
1775         return (i >>> distance) | (i << -distance);
1776     }
1777 
1778     /**
1779      * Returns the value obtained by reversing the order of the bits in the
1780      * two's complement binary representation of the specified {@code int}
1781      * value.
1782      *
1783      * @param i the value to be reversed
1784      * @return the value obtained by reversing order of the bits in the
1785      *     specified {@code int} value.
1786      * @since 1.5
1787      */
1788     public static int reverse(int i) {
1789         // HD, Figure 7-1
1790         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1791         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1792         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1793 
1794         return reverseBytes(i);
1795     }
1796 
1797     /**
1798      * Returns the signum function of the specified {@code int} value.  (The
1799      * return value is -1 if the specified value is negative; 0 if the
1800      * specified value is zero; and 1 if the specified value is positive.)
1801      *
1802      * @param i the value whose signum is to be computed
1803      * @return the signum function of the specified {@code int} value.
1804      * @since 1.5
1805      */
1806     public static int signum(int i) {
1807         // HD, Section 2-7
1808         return (i >> 31) | (-i >>> 31);
1809     }
1810 
1811     /**
1812      * Returns the value obtained by reversing the order of the bytes in the
1813      * two's complement representation of the specified {@code int} value.
1814      *
1815      * @param i the value whose bytes are to be reversed
1816      * @return the value obtained by reversing the bytes in the specified
1817      *     {@code int} value.
1818      * @since 1.5
1819      */
1820     @HotSpotIntrinsicCandidate
1821     public static int reverseBytes(int i) {
1822         return (i << 24)            |
1823                ((i & 0xff00) << 8)  |
1824                ((i >>> 8) & 0xff00) |
1825                (i >>> 24);
1826     }
1827 
1828     /**
1829      * Adds two integers together as per the + operator.
1830      *
1831      * @param a the first operand
1832      * @param b the second operand
1833      * @return the sum of {@code a} and {@code b}
1834      * @see java.util.function.BinaryOperator
1835      * @since 1.8
1836      */
1837     public static int sum(int a, int b) {
1838         return a + b;
1839     }
1840 
1841     /**
1842      * Returns the greater of two {@code int} values
1843      * as if by calling {@link Math#max(int, int) Math.max}.
1844      *
1845      * @param a the first operand
1846      * @param b the second operand
1847      * @return the greater of {@code a} and {@code b}
1848      * @see java.util.function.BinaryOperator
1849      * @since 1.8
1850      */
1851     public static int max(int a, int b) {
1852         return Math.max(a, b);
1853     }
1854 
1855     /**
1856      * Returns the smaller of two {@code int} values
1857      * as if by calling {@link Math#min(int, int) Math.min}.
1858      *
1859      * @param a the first operand
1860      * @param b the second operand
1861      * @return the smaller of {@code a} and {@code b}
1862      * @see java.util.function.BinaryOperator
1863      * @since 1.8
1864      */
1865     public static int min(int a, int b) {
1866         return Math.min(a, b);
1867     }
1868 
1869     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1870     @Native private static final long serialVersionUID = 1360826667806852920L;
1871 }