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