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