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