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