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