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  * @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     private static final class IntegerCache {
 908         static final int low = -128;
 909         static final int high;
 910 
 911         @Stable
 912         static final Integer[] cache;
 913         static Integer[] archivedCache;
 914 
 915         static {
 916             // high value may be configured by property
 917             int h = 127;
 918             String integerCacheHighPropValue =
 919                 VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 920             if (integerCacheHighPropValue != null) {
 921                 try {
 922                     h = Math.max(parseInt(integerCacheHighPropValue), 127);
 923                     // Maximum array size is Integer.MAX_VALUE
 924                     h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
 925                 } catch( NumberFormatException nfe) {
 926                     // If the property cannot be parsed into an int, ignore it.
 927                 }
 928             }
 929             high = h;
 930 
 931             // Load IntegerCache.archivedCache from archive, if possible
 932             CDS.initializeFromArchive(IntegerCache.class);
 933             int size = (high - low) + 1;
 934 
 935             // Use the archived cache if it exists and is large enough
 936             if (archivedCache == null || size > archivedCache.length) {
 937                 Integer[] c = new Integer[size];
 938                 int j = low;
 939                 // If archive has Integer cache, we must use all instances from it.
 940                 // Otherwise, the identity checks between archived Integers and
 941                 // runtime-cached Integers would fail.
 942                 int archivedSize = (archivedCache == null) ? 0 : archivedCache.length;
 943                 for (int i = 0; i < archivedSize; i++) {
 944                     c[i] = archivedCache[i];
 945                     assert j == archivedCache[i];
 946                     j++;
 947                 }
 948                 // Fill the rest of the cache.
 949                 for (int i = archivedSize; i < size; i++) {
 950                     c[i] = new Integer(j++);
 951                 }
 952                 archivedCache = c;
 953             }
 954             cache = archivedCache;
 955             // range [-128, 127] must be interned (JLS7 5.1.7)
 956             assert IntegerCache.high >= 127;
 957         }
 958 
 959         private IntegerCache() {}
 960     }
 961 
 962     /**
 963      * Returns an {@code Integer} instance representing the specified
 964      * {@code int} value.
 965      * <div class="preview-block">
 966      *      <div class="preview-comment">
 967      *          <p>
 968      *              - When preview features are NOT enabled, {@code Integer} is an identity class.
 969      *              If a new {@code Integer} instance is not
 970      *              required, this method should generally be used in preference to
 971      *              the constructor {@link #Integer(int)}, as this method is likely
 972      *              to yield significantly better space and time performance by
 973      *              caching frequently requested values.
 974      *              This method will always cache values in the range -128 to 127,
 975      *              inclusive, and may cache other values outside of this range.
 976      *          </p>
 977      *          <p>
 978      *              - When preview features are enabled, {@code Integer} is a {@linkplain Class#isValue value class}.
 979      *              The {@code valueOf} behavior is the same as invoking the constructor,
 980      *              whether cached or not.
 981      *          </p>
 982      *      </div>
 983      * </div>
 984      *
 985      * @param  i an {@code int} value.
 986      * @return an {@code Integer} instance representing {@code i}.
 987      * @since  1.5
 988      */
 989     @IntrinsicCandidate
 990     @DeserializeConstructor
 991     public static Integer valueOf(int i) {
 992         if (!PreviewFeatures.isEnabled()) {
 993             if (i >= IntegerCache.low && i <= IntegerCache.high)
 994                 return IntegerCache.cache[i + (-IntegerCache.low)];
 995         }
 996         return new Integer(i);
 997     }
 998 
 999     /**
1000      * The value of the {@code Integer}.
1001      *
1002      * @serial
1003      */
1004     private final int value;
1005 
1006     /**
1007      * Constructs a newly allocated {@code Integer} object that
1008      * represents the specified {@code int} value.
1009      *
1010      * @param   value   the value to be represented by the
1011      *                  {@code Integer} object.
1012      *
1013      * @deprecated
1014      * It is rarely appropriate to use this constructor. The static factory
1015      * {@link #valueOf(int)} is generally a better choice, as it is
1016      * likely to yield significantly better space and time performance.
1017      */
1018     @Deprecated(since="9")
1019     public Integer(int value) {
1020         this.value = value;
1021     }
1022 
1023     /**
1024      * Constructs a newly allocated {@code Integer} object that
1025      * represents the {@code int} value indicated by the
1026      * {@code String} parameter. The string is converted to an
1027      * {@code int} value in exactly the manner used by the
1028      * {@code parseInt} method for radix 10.
1029      *
1030      * @param   s   the {@code String} to be converted to an {@code Integer}.
1031      * @throws      NumberFormatException if the {@code String} does not
1032      *              contain a parsable integer.
1033      *
1034      * @deprecated
1035      * It is rarely appropriate to use this constructor.
1036      * Use {@link #parseInt(String)} to convert a string to a
1037      * {@code int} primitive, or use {@link #valueOf(String)}
1038      * to convert a string to an {@code Integer} object.
1039      */
1040     @Deprecated(since="9")
1041     public Integer(String s) throws NumberFormatException {
1042         this.value = parseInt(s, 10);
1043     }
1044 
1045     /**
1046      * Returns the value of this {@code Integer} as a {@code byte}
1047      * after a narrowing primitive conversion.
1048      * @jls 5.1.3 Narrowing Primitive Conversion
1049      */
1050     public byte byteValue() {
1051         return (byte)value;
1052     }
1053 
1054     /**
1055      * Returns the value of this {@code Integer} as a {@code short}
1056      * after a narrowing primitive conversion.
1057      * @jls 5.1.3 Narrowing Primitive Conversion
1058      */
1059     public short shortValue() {
1060         return (short)value;
1061     }
1062 
1063     /**
1064      * Returns the value of this {@code Integer} as an
1065      * {@code int}.
1066      */
1067     @IntrinsicCandidate
1068     public int intValue() {
1069         return value;
1070     }
1071 
1072     /**
1073      * Returns the value of this {@code Integer} as a {@code long}
1074      * after a widening primitive conversion.
1075      * @jls 5.1.2 Widening Primitive Conversion
1076      * @see Integer#toUnsignedLong(int)
1077      */
1078     public long longValue() {
1079         return (long)value;
1080     }
1081 
1082     /**
1083      * Returns the value of this {@code Integer} as a {@code float}
1084      * after a widening primitive conversion.
1085      * @jls 5.1.2 Widening Primitive Conversion
1086      */
1087     public float floatValue() {
1088         return (float)value;
1089     }
1090 
1091     /**
1092      * Returns the value of this {@code Integer} as a {@code double}
1093      * after a widening primitive conversion.
1094      * @jls 5.1.2 Widening Primitive Conversion
1095      */
1096     public double doubleValue() {
1097         return (double)value;
1098     }
1099 
1100     /**
1101      * Returns a {@code String} object representing this
1102      * {@code Integer}'s value. The value is converted to signed
1103      * decimal representation and returned as a string, exactly as if
1104      * the integer value were given as an argument to the {@link
1105      * java.lang.Integer#toString(int)} method.
1106      *
1107      * @return  a string representation of the value of this object in
1108      *          base&nbsp;10.
1109      */
1110     public String toString() {
1111         return toString(value);
1112     }
1113 
1114     /**
1115      * Returns a hash code for this {@code Integer}.
1116      *
1117      * @return  a hash code value for this object, equal to the
1118      *          primitive {@code int} value represented by this
1119      *          {@code Integer} object.
1120      */
1121     @Override
1122     public int hashCode() {
1123         return Integer.hashCode(value);
1124     }
1125 
1126     /**
1127      * Returns a hash code for an {@code int} value; compatible with
1128      * {@code Integer.hashCode()}.
1129      *
1130      * @param value the value to hash
1131      * @since 1.8
1132      *
1133      * @return a hash code value for an {@code int} value.
1134      */
1135     public static int hashCode(int value) {
1136         return value;
1137     }
1138 
1139     /**
1140      * Compares this object to the specified object.  The result is
1141      * {@code true} if and only if the argument is not
1142      * {@code null} and is an {@code Integer} object that
1143      * contains the same {@code int} value as this object.
1144      *
1145      * @param   obj   the object to compare with.
1146      * @return  {@code true} if the objects are the same;
1147      *          {@code false} otherwise.
1148      */
1149     public boolean equals(Object obj) {
1150         if (obj instanceof Integer i) {
1151             return value == i.intValue();
1152         }
1153         return false;
1154     }
1155 
1156     /**
1157      * Determines the integer value of the system property with the
1158      * specified name.
1159      *
1160      * <p>The first argument is treated as the name of a system
1161      * property.  System properties are accessible through the {@link
1162      * java.lang.System#getProperty(java.lang.String)} method. The
1163      * string value of this property is then interpreted as an integer
1164      * value using the grammar supported by {@link Integer#decode decode} and
1165      * an {@code Integer} object representing this value is returned.
1166      *
1167      * <p>If there is no property with the specified name, if the
1168      * specified name is empty or {@code null}, or if the property
1169      * does not have the correct numeric format, then {@code null} is
1170      * returned.
1171      *
1172      * <p>In other words, this method returns an {@code Integer}
1173      * object equal to the value of:
1174      *
1175      * <blockquote>
1176      *  {@code getInteger(nm, null)}
1177      * </blockquote>
1178      *
1179      * @param   nm   property name.
1180      * @return  the {@code Integer} value of the property.
1181      * @see     java.lang.System#getProperty(java.lang.String)
1182      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1183      */
1184     public static Integer getInteger(String nm) {
1185         return getInteger(nm, null);
1186     }
1187 
1188     /**
1189      * Determines the integer value of the system property with the
1190      * specified name.
1191      *
1192      * <p>The first argument is treated as the name of a system
1193      * property.  System properties are accessible through the {@link
1194      * java.lang.System#getProperty(java.lang.String)} method. The
1195      * string value of this property is then interpreted as an integer
1196      * value using the grammar supported by {@link Integer#decode decode} and
1197      * an {@code Integer} object representing this value is returned.
1198      *
1199      * <p>The second argument is the default value. An {@code Integer} object
1200      * that represents the value of the second argument is returned if there
1201      * is no property of the specified name, if the property does not have
1202      * the correct numeric format, or if the specified name is empty or
1203      * {@code null}.
1204      *
1205      * <p>In other words, this method returns an {@code Integer} object
1206      * equal to the value of:
1207      *
1208      * <blockquote>
1209      *  {@code getInteger(nm, Integer.valueOf(val))}
1210      * </blockquote>
1211      *
1212      * but in practice it may be implemented in a manner such as:
1213      *
1214      * <blockquote><pre>
1215      * Integer result = getInteger(nm, null);
1216      * return (result == null) ? Integer.valueOf(val) : result;
1217      * </pre></blockquote>
1218      *
1219      * to avoid the unnecessary allocation of an {@code Integer}
1220      * object when the default value is not needed.
1221      *
1222      * @param   nm   property name.
1223      * @param   val   default value.
1224      * @return  the {@code Integer} value of the property.
1225      * @see     java.lang.System#getProperty(java.lang.String)
1226      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1227      */
1228     public static Integer getInteger(String nm, int val) {
1229         Integer result = getInteger(nm, null);
1230         return (result == null) ? Integer.valueOf(val) : result;
1231     }
1232 
1233     /**
1234      * Returns the integer value of the system property with the
1235      * specified name.  The first argument is treated as the name of a
1236      * system property.  System properties are accessible through the
1237      * {@link java.lang.System#getProperty(java.lang.String)} method.
1238      * The string value of this property is then interpreted as an
1239      * integer value, as per the {@link Integer#decode decode} method,
1240      * and an {@code Integer} object representing this value is
1241      * returned; in summary:
1242      *
1243      * <ul><li>If the property value begins with the two ASCII characters
1244      *         {@code 0x} or the ASCII character {@code #}, not
1245      *      followed by a minus sign, then the rest of it is parsed as a
1246      *      hexadecimal integer exactly as by the method
1247      *      {@link #valueOf(java.lang.String, int)} with radix 16.
1248      * <li>If the property value begins with the ASCII character
1249      *     {@code 0} followed by another character, it is parsed as an
1250      *     octal integer exactly as by the method
1251      *     {@link #valueOf(java.lang.String, int)} with radix 8.
1252      * <li>Otherwise, the property value is parsed as a decimal integer
1253      * exactly as by the method {@link #valueOf(java.lang.String, int)}
1254      * with radix 10.
1255      * </ul>
1256      *
1257      * <p>The second argument is the default value. The default value is
1258      * returned if there is no property of the specified name, if the
1259      * property does not have the correct numeric format, or if the
1260      * specified name is empty or {@code null}.
1261      *
1262      * @param   nm   property name.
1263      * @param   val   default value.
1264      * @return  the {@code Integer} value of the property.
1265      * @see     System#getProperty(java.lang.String)
1266      * @see     System#getProperty(java.lang.String, java.lang.String)
1267      */
1268     public static Integer getInteger(String nm, Integer val) {
1269         String v = nm != null && !nm.isEmpty() ? System.getProperty(nm) : null;
1270         if (v != null) {
1271             try {
1272                 return Integer.decode(v);
1273             } catch (NumberFormatException e) {
1274             }
1275         }
1276         return val;
1277     }
1278 
1279     /**
1280      * Decodes a {@code String} into an {@code Integer}.
1281      * Accepts decimal, hexadecimal, and octal numbers given
1282      * by the following grammar:
1283      *
1284      * <blockquote>
1285      * <dl>
1286      * <dt><i>DecodableString:</i>
1287      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1288      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1289      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1290      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1291      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1292      *
1293      * <dt><i>Sign:</i>
1294      * <dd>{@code -}
1295      * <dd>{@code +}
1296      * </dl>
1297      * </blockquote>
1298      *
1299      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1300      * are as defined in section {@jls 3.10.1} of
1301      * <cite>The Java Language Specification</cite>,
1302      * except that underscores are not accepted between digits.
1303      *
1304      * <p>The sequence of characters following an optional
1305      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1306      * "{@code #}", or leading zero) is parsed as by the {@code
1307      * Integer.parseInt} method with the indicated radix (10, 16, or
1308      * 8).  This sequence of characters must represent a positive
1309      * value or a {@link NumberFormatException} will be thrown.  The
1310      * result is negated if first character of the specified {@code
1311      * String} is the minus sign.  No whitespace characters are
1312      * permitted in the {@code String}.
1313      *
1314      * @param     nm the {@code String} to decode.
1315      * @return    an {@code Integer} object holding the {@code int}
1316      *             value represented by {@code nm}
1317      * @throws    NumberFormatException  if the {@code String} does not
1318      *            contain a parsable integer.
1319      * @see java.lang.Integer#parseInt(java.lang.String, int)
1320      */
1321     public static Integer decode(String nm) throws NumberFormatException {
1322         int radix = 10;
1323         int index = 0;
1324         boolean negative = false;
1325         int result;
1326 
1327         if (nm.isEmpty())
1328             throw new NumberFormatException("Zero length string");
1329         char firstChar = nm.charAt(0);
1330         // Handle sign, if present
1331         if (firstChar == '-') {
1332             negative = true;
1333             index++;
1334         } else if (firstChar == '+')
1335             index++;
1336 
1337         // Handle radix specifier, if present
1338         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1339             index += 2;
1340             radix = 16;
1341         }
1342         else if (nm.startsWith("#", index)) {
1343             index ++;
1344             radix = 16;
1345         }
1346         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1347             index ++;
1348             radix = 8;
1349         }
1350 
1351         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1352             throw new NumberFormatException("Sign character in wrong position");
1353 
1354         try {
1355             result = parseInt(nm, index, nm.length(), radix);
1356             result = negative ? -result : result;
1357         } catch (NumberFormatException e) {
1358             // If number is Integer.MIN_VALUE, we'll end up here. The next line
1359             // handles this case, and causes any genuine format error to be
1360             // rethrown.
1361             String constant = negative ? ("-" + nm.substring(index))
1362                                        : nm.substring(index);
1363             result = parseInt(constant, radix);
1364         }
1365         return result;
1366     }
1367 
1368     /**
1369      * Compares two {@code Integer} objects numerically.
1370      *
1371      * @param   anotherInteger   the {@code Integer} to be compared.
1372      * @return  the value {@code 0} if this {@code Integer} is
1373      *          equal to the argument {@code Integer}; a value less than
1374      *          {@code 0} if this {@code Integer} is numerically less
1375      *          than the argument {@code Integer}; and a value greater
1376      *          than {@code 0} if this {@code Integer} is numerically
1377      *           greater than the argument {@code Integer} (signed
1378      *           comparison).
1379      * @since   1.2
1380      */
1381     public int compareTo(Integer anotherInteger) {
1382         return compare(this.value, anotherInteger.value);
1383     }
1384 
1385     /**
1386      * Compares two {@code int} values numerically.
1387      * The value returned is identical to what would be returned by:
1388      * <pre>
1389      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
1390      * </pre>
1391      *
1392      * @param  x the first {@code int} to compare
1393      * @param  y the second {@code int} to compare
1394      * @return the value {@code 0} if {@code x == y};
1395      *         a value less than {@code 0} if {@code x < y}; and
1396      *         a value greater than {@code 0} if {@code x > y}
1397      * @since 1.7
1398      */
1399     public static int compare(int x, int y) {
1400         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1401     }
1402 
1403     /**
1404      * Compares two {@code int} values numerically treating the values
1405      * as unsigned.
1406      *
1407      * @param  x the first {@code int} to compare
1408      * @param  y the second {@code int} to compare
1409      * @return the value {@code 0} if {@code x == y}; a value less
1410      *         than {@code 0} if {@code x < y} as unsigned values; and
1411      *         a value greater than {@code 0} if {@code x > y} as
1412      *         unsigned values
1413      * @since 1.8
1414      */
1415     @IntrinsicCandidate
1416     public static int compareUnsigned(int x, int y) {
1417         return compare(x + MIN_VALUE, y + MIN_VALUE);
1418     }
1419 
1420     /**
1421      * Converts the argument to a {@code long} by an unsigned
1422      * conversion.  In an unsigned conversion to a {@code long}, the
1423      * high-order 32 bits of the {@code long} are zero and the
1424      * low-order 32 bits are equal to the bits of the integer
1425      * argument.
1426      *
1427      * Consequently, zero and positive {@code int} values are mapped
1428      * to a numerically equal {@code long} value and negative {@code
1429      * int} values are mapped to a {@code long} value equal to the
1430      * input plus 2<sup>32</sup>.
1431      *
1432      * @param  x the value to convert to an unsigned {@code long}
1433      * @return the argument converted to {@code long} by an unsigned
1434      *         conversion
1435      * @since 1.8
1436      */
1437     public static long toUnsignedLong(int x) {
1438         return ((long) x) & 0xffffffffL;
1439     }
1440 
1441     /**
1442      * Returns the unsigned quotient of dividing the first argument by
1443      * the second where each argument and the result is interpreted as
1444      * an unsigned value.
1445      *
1446      * <p>Note that in two's complement arithmetic, the three other
1447      * basic arithmetic operations of add, subtract, and multiply are
1448      * bit-wise identical if the two operands are regarded as both
1449      * being signed or both being unsigned.  Therefore separate {@code
1450      * addUnsigned}, etc. methods are not provided.
1451      *
1452      * @param dividend the value to be divided
1453      * @param divisor the value doing the dividing
1454      * @return the unsigned quotient of the first argument divided by
1455      * the second argument
1456      * @see #remainderUnsigned
1457      * @since 1.8
1458      */
1459     @IntrinsicCandidate
1460     public static int divideUnsigned(int dividend, int divisor) {
1461         // In lieu of tricky code, for now just use long arithmetic.
1462         return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
1463     }
1464 
1465     /**
1466      * Returns the unsigned remainder from dividing the first argument
1467      * by the second where each argument and the result is interpreted
1468      * as an unsigned value.
1469      *
1470      * @param dividend the value to be divided
1471      * @param divisor the value doing the dividing
1472      * @return the unsigned remainder of the first argument divided by
1473      * the second argument
1474      * @see #divideUnsigned
1475      * @since 1.8
1476      */
1477     @IntrinsicCandidate
1478     public static int remainderUnsigned(int dividend, int divisor) {
1479         // In lieu of tricky code, for now just use long arithmetic.
1480         return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
1481     }
1482 
1483 
1484     // Bit twiddling
1485 
1486     /**
1487      * The number of bits used to represent an {@code int} value in two's
1488      * complement binary form.
1489      *
1490      * @since 1.5
1491      */
1492     @Native public static final int SIZE = 32;
1493 
1494     /**
1495      * The number of bytes used to represent an {@code int} value in two's
1496      * complement binary form.
1497      *
1498      * @since 1.8
1499      */
1500     public static final int BYTES = SIZE / Byte.SIZE;
1501 
1502     /**
1503      * Returns an {@code int} value with at most a single one-bit, in the
1504      * position of the highest-order ("leftmost") one-bit in the specified
1505      * {@code int} value.  Returns zero if the specified value has no
1506      * one-bits in its two's complement binary representation, that is, if it
1507      * is equal to zero.
1508      *
1509      * @param i the value whose highest one bit is to be computed
1510      * @return an {@code int} value with a single one-bit, in the position
1511      *     of the highest-order one-bit in the specified value, or zero if
1512      *     the specified value is itself equal to zero.
1513      * @since 1.5
1514      */
1515     public static int highestOneBit(int i) {
1516         return i & (MIN_VALUE >>> numberOfLeadingZeros(i));
1517     }
1518 
1519     /**
1520      * Returns an {@code int} value with at most a single one-bit, in the
1521      * position of the lowest-order ("rightmost") one-bit in the specified
1522      * {@code int} value.  Returns zero if the specified value has no
1523      * one-bits in its two's complement binary representation, that is, if it
1524      * is equal to zero.
1525      *
1526      * @param i the value whose lowest one bit is to be computed
1527      * @return an {@code int} value with a single one-bit, in the position
1528      *     of the lowest-order one-bit in the specified value, or zero if
1529      *     the specified value is itself equal to zero.
1530      * @since 1.5
1531      */
1532     public static int lowestOneBit(int i) {
1533         // HD, Section 2-1
1534         return i & -i;
1535     }
1536 
1537     /**
1538      * Returns the number of zero bits preceding the highest-order
1539      * ("leftmost") one-bit in the two's complement binary representation
1540      * of the specified {@code int} value.  Returns 32 if the
1541      * specified value has no one-bits in its two's complement representation,
1542      * in other words if it is equal to zero.
1543      *
1544      * <p>Note that this method is closely related to the logarithm base 2.
1545      * For all positive {@code int} values x:
1546      * <ul>
1547      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1548      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1549      * </ul>
1550      *
1551      * @param i the value whose number of leading zeros is to be computed
1552      * @return the number of zero bits preceding the highest-order
1553      *     ("leftmost") one-bit in the two's complement binary representation
1554      *     of the specified {@code int} value, or 32 if the value
1555      *     is equal to zero.
1556      * @since 1.5
1557      */
1558     @IntrinsicCandidate
1559     public static int numberOfLeadingZeros(int i) {
1560         // HD, Count leading 0's
1561         if (i <= 0)
1562             return i == 0 ? 32 : 0;
1563         int n = 31;
1564         if (i >= 1 << 16) { n -= 16; i >>>= 16; }
1565         if (i >= 1 <<  8) { n -=  8; i >>>=  8; }
1566         if (i >= 1 <<  4) { n -=  4; i >>>=  4; }
1567         if (i >= 1 <<  2) { n -=  2; i >>>=  2; }
1568         return n - (i >>> 1);
1569     }
1570 
1571     /**
1572      * Returns the number of zero bits following the lowest-order ("rightmost")
1573      * one-bit in the two's complement binary representation of the specified
1574      * {@code int} value.  Returns 32 if the specified value has no
1575      * one-bits in its two's complement representation, in other words if it is
1576      * equal to zero.
1577      *
1578      * @param i the value whose number of trailing zeros is to be computed
1579      * @return the number of zero bits following the lowest-order ("rightmost")
1580      *     one-bit in the two's complement binary representation of the
1581      *     specified {@code int} value, or 32 if the value is equal
1582      *     to zero.
1583      * @since 1.5
1584      */
1585     @IntrinsicCandidate
1586     public static int numberOfTrailingZeros(int i) {
1587         // HD, Count trailing 0's
1588         i = ~i & (i - 1);
1589         if (i <= 0) return i & 32;
1590         int n = 1;
1591         if (i > 1 << 16) { n += 16; i >>>= 16; }
1592         if (i > 1 <<  8) { n +=  8; i >>>=  8; }
1593         if (i > 1 <<  4) { n +=  4; i >>>=  4; }
1594         if (i > 1 <<  2) { n +=  2; i >>>=  2; }
1595         return n + (i >>> 1);
1596     }
1597 
1598     /**
1599      * Returns the number of one-bits in the two's complement binary
1600      * representation of the specified {@code int} value.  This function is
1601      * sometimes referred to as the <i>population count</i>.
1602      *
1603      * @param i the value whose bits are to be counted
1604      * @return the number of one-bits in the two's complement binary
1605      *     representation of the specified {@code int} value.
1606      * @since 1.5
1607      */
1608     @IntrinsicCandidate
1609     public static int bitCount(int i) {
1610         // HD, Figure 5-2
1611         i = i - ((i >>> 1) & 0x55555555);
1612         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1613         i = (i + (i >>> 4)) & 0x0f0f0f0f;
1614         i = i + (i >>> 8);
1615         i = i + (i >>> 16);
1616         return i & 0x3f;
1617     }
1618 
1619     /**
1620      * Returns the value obtained by rotating the two's complement binary
1621      * representation of the specified {@code int} value left by the
1622      * specified number of bits.  (Bits shifted out of the left hand, or
1623      * high-order, side reenter on the right, or low-order.)
1624      *
1625      * <p>Note that left rotation with a negative distance is equivalent to
1626      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1627      * distance)}.  Note also that rotation by any multiple of 32 is a
1628      * no-op, so all but the last five bits of the rotation distance can be
1629      * ignored, even if the distance is negative: {@code rotateLeft(val,
1630      * distance) == rotateLeft(val, distance & 0x1F)}.
1631      *
1632      * @param i the value whose bits are to be rotated left
1633      * @param distance the number of bit positions to rotate left
1634      * @return the value obtained by rotating the two's complement binary
1635      *     representation of the specified {@code int} value left by the
1636      *     specified number of bits.
1637      * @since 1.5
1638      */
1639     public static int rotateLeft(int i, int distance) {
1640         return (i << distance) | (i >>> -distance);
1641     }
1642 
1643     /**
1644      * Returns the value obtained by rotating the two's complement binary
1645      * representation of the specified {@code int} value right by the
1646      * specified number of bits.  (Bits shifted out of the right hand, or
1647      * low-order, side reenter on the left, or high-order.)
1648      *
1649      * <p>Note that right rotation with a negative distance is equivalent to
1650      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1651      * distance)}.  Note also that rotation by any multiple of 32 is a
1652      * no-op, so all but the last five bits of the rotation distance can be
1653      * ignored, even if the distance is negative: {@code rotateRight(val,
1654      * distance) == rotateRight(val, distance & 0x1F)}.
1655      *
1656      * @param i the value whose bits are to be rotated right
1657      * @param distance the number of bit positions to rotate right
1658      * @return the value obtained by rotating the two's complement binary
1659      *     representation of the specified {@code int} value right by the
1660      *     specified number of bits.
1661      * @since 1.5
1662      */
1663     public static int rotateRight(int i, int distance) {
1664         return (i >>> distance) | (i << -distance);
1665     }
1666 
1667     /**
1668      * Returns the value obtained by reversing the order of the bits in the
1669      * two's complement binary representation of the specified {@code int}
1670      * value.
1671      *
1672      * @param i the value to be reversed
1673      * @return the value obtained by reversing order of the bits in the
1674      *     specified {@code int} value.
1675      * @since 1.5
1676      */
1677     @IntrinsicCandidate
1678     public static int reverse(int i) {
1679         // HD, Figure 7-1
1680         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1681         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1682         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1683 
1684         return reverseBytes(i);
1685     }
1686 
1687     /**
1688      * Returns the value obtained by compressing the bits of the
1689      * specified {@code int} value, {@code i}, in accordance with
1690      * the specified bit mask.
1691      * <p>
1692      * For each one-bit value {@code mb} of the mask, from least
1693      * significant to most significant, the bit value of {@code i} at
1694      * the same bit location as {@code mb} is assigned to the compressed
1695      * value contiguously starting from the least significant bit location.
1696      * All the upper remaining bits of the compressed value are set
1697      * to zero.
1698      *
1699      * @apiNote
1700      * Consider the simple case of compressing the digits of a hexadecimal
1701      * value:
1702      * {@snippet lang="java" :
1703      * // Compressing drink to food
1704      * compress(0xCAFEBABE, 0xFF00FFF0) == 0xCABAB
1705      * }
1706      * Starting from the least significant hexadecimal digit at position 0
1707      * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits
1708      * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits
1709      * occur in the resulting compressed value contiguously from digit position
1710      * 0 in the same order.
1711      * <p>
1712      * The following identities all return {@code true} and are helpful to
1713      * understand the behaviour of {@code compress}:
1714      * {@snippet lang="java" :
1715      * // Returns 1 if the bit at position n is one
1716      * compress(x, 1 << n) == (x >> n & 1)
1717      *
1718      * // Logical shift right
1719      * compress(x, -1 << n) == x >>> n
1720      *
1721      * // Any bits not covered by the mask are ignored
1722      * compress(x, m) == compress(x & m, m)
1723      *
1724      * // Compressing a value by itself
1725      * compress(m, m) == (m == -1 || m == 0) ? m : (1 << bitCount(m)) - 1
1726      *
1727      * // Expanding then compressing with the same mask
1728      * compress(expand(x, m), m) == x & compress(m, m)
1729      * }
1730      * <p>
1731      * The Sheep And Goats (SAG) operation (see Hacker's Delight, Second Edition, section 7.7)
1732      * can be implemented as follows:
1733      * {@snippet lang="java" :
1734      * int compressLeft(int i, int mask) {
1735      *     // This implementation follows the description in Hacker's Delight which
1736      *     // is informative. A more optimal implementation is:
1737      *     //   Integer.compress(i, mask) << -Integer.bitCount(mask)
1738      *     return Integer.reverse(
1739      *         Integer.compress(Integer.reverse(i), Integer.reverse(mask)));
1740      * }
1741      *
1742      * int sag(int i, int mask) {
1743      *     return compressLeft(i, mask) | Integer.compress(i, ~mask);
1744      * }
1745      *
1746      * // Separate the sheep from the goats
1747      * sag(0xCAFEBABE, 0xFF00FFF0) == 0xCABABFEE
1748      * }
1749      *
1750      * @param i the value whose bits are to be compressed
1751      * @param mask the bit mask
1752      * @return the compressed value
1753      * @see #expand
1754      * @since 19
1755      */
1756     @IntrinsicCandidate
1757     public static int compress(int i, int mask) {
1758         // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract
1759 
1760         i = i & mask; // Clear irrelevant bits
1761         int maskCount = ~mask << 1; // Count 0's to right
1762 
1763         for (int j = 0; j < 5; j++) {
1764             // Parallel prefix
1765             // Mask prefix identifies bits of the mask that have an odd number of 0's to the right
1766             int maskPrefix = parallelSuffix(maskCount);
1767             // Bits to move
1768             int maskMove = maskPrefix & mask;
1769             // Compress mask
1770             mask = (mask ^ maskMove) | (maskMove >>> (1 << j));
1771             // Bits of i to be moved
1772             int t = i & maskMove;
1773             // Compress i
1774             i = (i ^ t) | (t >>> (1 << j));
1775             // Adjust the mask count by identifying bits that have 0 to the right
1776             maskCount = maskCount & ~maskPrefix;
1777         }
1778         return i;
1779     }
1780 
1781     /**
1782      * Returns the value obtained by expanding the bits of the
1783      * specified {@code int} value, {@code i}, in accordance with
1784      * the specified bit mask.
1785      * <p>
1786      * For each one-bit value {@code mb} of the mask, from least
1787      * significant to most significant, the next contiguous bit value
1788      * of {@code i} starting at the least significant bit is assigned
1789      * to the expanded value at the same bit location as {@code mb}.
1790      * All other remaining bits of the expanded value are set to zero.
1791      *
1792      * @apiNote
1793      * Consider the simple case of expanding the digits of a hexadecimal
1794      * value:
1795      * {@snippet lang="java" :
1796      * expand(0x0000CABAB, 0xFF00FFF0) == 0xCA00BAB0
1797      * }
1798      * Starting from the least significant hexadecimal digit at position 0
1799      * from the right, the mask {@code 0xFF00FFF0} selects the first five
1800      * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur
1801      * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7.
1802      * <p>
1803      * The following identities all return {@code true} and are helpful to
1804      * understand the behaviour of {@code expand}:
1805      * {@snippet lang="java" :
1806      * // Logically shift right the bit at position 0
1807      * expand(x, 1 << n) == (x & 1) << n
1808      *
1809      * // Logically shift right
1810      * expand(x, -1 << n) == x << n
1811      *
1812      * // Expanding all bits returns the mask
1813      * expand(-1, m) == m
1814      *
1815      * // Any bits not covered by the mask are ignored
1816      * expand(x, m) == expand(x, m) & m
1817      *
1818      * // Compressing then expanding with the same mask
1819      * expand(compress(x, m), m) == x & m
1820      * }
1821      * <p>
1822      * The select operation for determining the position of the one-bit with
1823      * index {@code n} in a {@code int} value can be implemented as follows:
1824      * {@snippet lang="java" :
1825      * int select(int i, int n) {
1826      *     // the one-bit in i (the mask) with index n
1827      *     int nthBit = Integer.expand(1 << n, i);
1828      *     // the bit position of the one-bit with index n
1829      *     return Integer.numberOfTrailingZeros(nthBit);
1830      * }
1831      *
1832      * // The one-bit with index 0 is at bit position 1
1833      * select(0b10101010_10101010, 0) == 1
1834      * // The one-bit with index 3 is at bit position 7
1835      * select(0b10101010_10101010, 3) == 7
1836      * }
1837      *
1838      * @param i the value whose bits are to be expanded
1839      * @param mask the bit mask
1840      * @return the expanded value
1841      * @see #compress
1842      * @since 19
1843      */
1844     @IntrinsicCandidate
1845     public static int expand(int i, int mask) {
1846         // Save original mask
1847         int originalMask = mask;
1848         // Count 0's to right
1849         int maskCount = ~mask << 1;
1850         int maskPrefix = parallelSuffix(maskCount);
1851         // Bits to move
1852         int maskMove1 = maskPrefix & mask;
1853         // Compress mask
1854         mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0));
1855         maskCount = maskCount & ~maskPrefix;
1856 
1857         maskPrefix = parallelSuffix(maskCount);
1858         // Bits to move
1859         int maskMove2 = maskPrefix & mask;
1860         // Compress mask
1861         mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1));
1862         maskCount = maskCount & ~maskPrefix;
1863 
1864         maskPrefix = parallelSuffix(maskCount);
1865         // Bits to move
1866         int maskMove3 = maskPrefix & mask;
1867         // Compress mask
1868         mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2));
1869         maskCount = maskCount & ~maskPrefix;
1870 
1871         maskPrefix = parallelSuffix(maskCount);
1872         // Bits to move
1873         int maskMove4 = maskPrefix & mask;
1874         // Compress mask
1875         mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3));
1876         maskCount = maskCount & ~maskPrefix;
1877 
1878         maskPrefix = parallelSuffix(maskCount);
1879         // Bits to move
1880         int maskMove5 = maskPrefix & mask;
1881 
1882         int t = i << (1 << 4);
1883         i = (i & ~maskMove5) | (t & maskMove5);
1884         t = i << (1 << 3);
1885         i = (i & ~maskMove4) | (t & maskMove4);
1886         t = i << (1 << 2);
1887         i = (i & ~maskMove3) | (t & maskMove3);
1888         t = i << (1 << 1);
1889         i = (i & ~maskMove2) | (t & maskMove2);
1890         t = i << (1 << 0);
1891         i = (i & ~maskMove1) | (t & maskMove1);
1892 
1893         // Clear irrelevant bits
1894         return i & originalMask;
1895     }
1896 
1897     @ForceInline
1898     private static int parallelSuffix(int maskCount) {
1899         int maskPrefix = maskCount ^ (maskCount << 1);
1900         maskPrefix = maskPrefix ^ (maskPrefix << 2);
1901         maskPrefix = maskPrefix ^ (maskPrefix << 4);
1902         maskPrefix = maskPrefix ^ (maskPrefix << 8);
1903         maskPrefix = maskPrefix ^ (maskPrefix << 16);
1904         return maskPrefix;
1905     }
1906 
1907     /**
1908      * Returns the signum function of the specified {@code int} value.  (The
1909      * return value is -1 if the specified value is negative; 0 if the
1910      * specified value is zero; and 1 if the specified value is positive.)
1911      *
1912      * @param i the value whose signum is to be computed
1913      * @return the signum function of the specified {@code int} value.
1914      * @since 1.5
1915      */
1916     public static int signum(int i) {
1917         // HD, Section 2-7
1918         return (i >> 31) | (-i >>> 31);
1919     }
1920 
1921     /**
1922      * Returns the value obtained by reversing the order of the bytes in the
1923      * two's complement representation of the specified {@code int} value.
1924      *
1925      * @param i the value whose bytes are to be reversed
1926      * @return the value obtained by reversing the bytes in the specified
1927      *     {@code int} value.
1928      * @since 1.5
1929      */
1930     @IntrinsicCandidate
1931     public static int reverseBytes(int i) {
1932         return (i << 24)            |
1933                ((i & 0xff00) << 8)  |
1934                ((i >>> 8) & 0xff00) |
1935                (i >>> 24);
1936     }
1937 
1938     /**
1939      * Adds two integers together as per the + operator.
1940      *
1941      * @param a the first operand
1942      * @param b the second operand
1943      * @return the sum of {@code a} and {@code b}
1944      * @see java.util.function.BinaryOperator
1945      * @since 1.8
1946      */
1947     public static int sum(int a, int b) {
1948         return a + b;
1949     }
1950 
1951     /**
1952      * Returns the greater of two {@code int} values
1953      * as if by calling {@link Math#max(int, int) Math.max}.
1954      *
1955      * @param a the first operand
1956      * @param b the second operand
1957      * @return the greater of {@code a} and {@code b}
1958      * @see java.util.function.BinaryOperator
1959      * @since 1.8
1960      */
1961     public static int max(int a, int b) {
1962         return Math.max(a, b);
1963     }
1964 
1965     /**
1966      * Returns the smaller of two {@code int} values
1967      * as if by calling {@link Math#min(int, int) Math.min}.
1968      *
1969      * @param a the first operand
1970      * @param b the second operand
1971      * @return the smaller of {@code a} and {@code b}
1972      * @see java.util.function.BinaryOperator
1973      * @since 1.8
1974      */
1975     public static int min(int a, int b) {
1976         return Math.min(a, b);
1977     }
1978 
1979     /**
1980      * Returns an {@link Optional} containing the nominal descriptor for this
1981      * instance, which is the instance itself.
1982      *
1983      * @return an {@link Optional} describing the {@linkplain Integer} instance
1984      * @since 12
1985      */
1986     @Override
1987     public Optional<Integer> describeConstable() {
1988         return Optional.of(this);
1989     }
1990 
1991     /**
1992      * Resolves this instance as a {@link ConstantDesc}, the result of which is
1993      * the instance itself.
1994      *
1995      * @param lookup ignored
1996      * @return the {@linkplain Integer} instance
1997      * @since 12
1998      */
1999     @Override
2000     public Integer resolveConstantDesc(MethodHandles.Lookup lookup) {
2001         return this;
2002     }
2003 
2004     /** use serialVersionUID from JDK 1.0.2 for interoperability */
2005     @java.io.Serial
2006     @Native private static final long serialVersionUID = 1360826667806852920L;
2007 }