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