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             StringLatin1.getChars(i, size, buf);
 446             return new String(buf, LATIN1);
 447         } else {
 448             byte[] buf = new byte[size * 2];
 449             StringUTF16.getChars(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      * @throws  SecurityException for the same reasons as
1202      *          {@link System#getProperty(String) System.getProperty}
1203      * @see     java.lang.System#getProperty(java.lang.String)
1204      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1205      */
1206     public static Integer getInteger(String nm) {
1207         return getInteger(nm, null);
1208     }
1209 
1210     /**
1211      * Determines the integer value of the system property with the
1212      * specified name.
1213      *
1214      * <p>The first argument is treated as the name of a system
1215      * property.  System properties are accessible through the {@link
1216      * java.lang.System#getProperty(java.lang.String)} method. The
1217      * string value of this property is then interpreted as an integer
1218      * value using the grammar supported by {@link Integer#decode decode} and
1219      * an {@code Integer} object representing this value is returned.
1220      *
1221      * <p>The second argument is the default value. An {@code Integer} object
1222      * that represents the value of the second argument is returned if there
1223      * is no property of the specified name, if the property does not have
1224      * the correct numeric format, or if the specified name is empty or
1225      * {@code null}.
1226      *
1227      * <p>In other words, this method returns an {@code Integer} object
1228      * equal to the value of:
1229      *
1230      * <blockquote>
1231      *  {@code getInteger(nm, Integer.valueOf(val))}
1232      * </blockquote>
1233      *
1234      * but in practice it may be implemented in a manner such as:
1235      *
1236      * <blockquote><pre>
1237      * Integer result = getInteger(nm, null);
1238      * return (result == null) ? Integer.valueOf(val) : result;
1239      * </pre></blockquote>
1240      *
1241      * to avoid the unnecessary allocation of an {@code Integer}
1242      * object when the default value is not needed.
1243      *
1244      * @param   nm   property name.
1245      * @param   val   default value.
1246      * @return  the {@code Integer} value of the property.
1247      * @throws  SecurityException for the same reasons as
1248      *          {@link System#getProperty(String) System.getProperty}
1249      * @see     java.lang.System#getProperty(java.lang.String)
1250      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1251      */
1252     public static Integer getInteger(String nm, int val) {
1253         Integer result = getInteger(nm, null);
1254         return (result == null) ? Integer.valueOf(val) : result;
1255     }
1256 
1257     /**
1258      * Returns the integer value of the system property with the
1259      * specified name.  The first argument is treated as the name of a
1260      * system property.  System properties are accessible through the
1261      * {@link java.lang.System#getProperty(java.lang.String)} method.
1262      * The string value of this property is then interpreted as an
1263      * integer value, as per the {@link Integer#decode decode} method,
1264      * and an {@code Integer} object representing this value is
1265      * returned; in summary:
1266      *
1267      * <ul><li>If the property value begins with the two ASCII characters
1268      *         {@code 0x} or the ASCII character {@code #}, not
1269      *      followed by a minus sign, then the rest of it is parsed as a
1270      *      hexadecimal integer exactly as by the method
1271      *      {@link #valueOf(java.lang.String, int)} with radix 16.
1272      * <li>If the property value begins with the ASCII character
1273      *     {@code 0} followed by another character, it is parsed as an
1274      *     octal integer exactly as by the method
1275      *     {@link #valueOf(java.lang.String, int)} with radix 8.
1276      * <li>Otherwise, the property value is parsed as a decimal integer
1277      * exactly as by the method {@link #valueOf(java.lang.String, int)}
1278      * with radix 10.
1279      * </ul>
1280      *
1281      * <p>The second argument is the default value. The default value is
1282      * returned if there is no property of the specified name, if the
1283      * property does not have the correct numeric format, or if the
1284      * specified name is empty or {@code null}.
1285      *
1286      * @param   nm   property name.
1287      * @param   val   default value.
1288      * @return  the {@code Integer} value of the property.
1289      * @throws  SecurityException for the same reasons as
1290      *          {@link System#getProperty(String) System.getProperty}
1291      * @see     System#getProperty(java.lang.String)
1292      * @see     System#getProperty(java.lang.String, java.lang.String)
1293      */
1294     public static Integer getInteger(String nm, Integer val) {
1295         String v = null;
1296         try {
1297             v = System.getProperty(nm);
1298         } catch (IllegalArgumentException | NullPointerException e) {
1299         }
1300         if (v != null) {
1301             try {
1302                 return Integer.decode(v);
1303             } catch (NumberFormatException e) {
1304             }
1305         }
1306         return val;
1307     }
1308 
1309     /**
1310      * Decodes a {@code String} into an {@code Integer}.
1311      * Accepts decimal, hexadecimal, and octal numbers given
1312      * by the following grammar:
1313      *
1314      * <blockquote>
1315      * <dl>
1316      * <dt><i>DecodableString:</i>
1317      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1318      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1319      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1320      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1321      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1322      *
1323      * <dt><i>Sign:</i>
1324      * <dd>{@code -}
1325      * <dd>{@code +}
1326      * </dl>
1327      * </blockquote>
1328      *
1329      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1330      * are as defined in section {@jls 3.10.1} of
1331      * <cite>The Java Language Specification</cite>,
1332      * except that underscores are not accepted between digits.
1333      *
1334      * <p>The sequence of characters following an optional
1335      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1336      * "{@code #}", or leading zero) is parsed as by the {@code
1337      * Integer.parseInt} method with the indicated radix (10, 16, or
1338      * 8).  This sequence of characters must represent a positive
1339      * value or a {@link NumberFormatException} will be thrown.  The
1340      * result is negated if first character of the specified {@code
1341      * String} is the minus sign.  No whitespace characters are
1342      * permitted in the {@code String}.
1343      *
1344      * @param     nm the {@code String} to decode.
1345      * @return    an {@code Integer} object holding the {@code int}
1346      *             value represented by {@code nm}
1347      * @throws    NumberFormatException  if the {@code String} does not
1348      *            contain a parsable integer.
1349      * @see java.lang.Integer#parseInt(java.lang.String, int)
1350      */
1351     public static Integer decode(String nm) throws NumberFormatException {
1352         int radix = 10;
1353         int index = 0;
1354         boolean negative = false;
1355         int result;
1356 
1357         if (nm.isEmpty())
1358             throw new NumberFormatException("Zero length string");
1359         char firstChar = nm.charAt(0);
1360         // Handle sign, if present
1361         if (firstChar == '-') {
1362             negative = true;
1363             index++;
1364         } else if (firstChar == '+')
1365             index++;
1366 
1367         // Handle radix specifier, if present
1368         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1369             index += 2;
1370             radix = 16;
1371         }
1372         else if (nm.startsWith("#", index)) {
1373             index ++;
1374             radix = 16;
1375         }
1376         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1377             index ++;
1378             radix = 8;
1379         }
1380 
1381         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1382             throw new NumberFormatException("Sign character in wrong position");
1383 
1384         try {
1385             result = parseInt(nm, index, nm.length(), radix);
1386             result = negative ? -result : result;
1387         } catch (NumberFormatException e) {
1388             // If number is Integer.MIN_VALUE, we'll end up here. The next line
1389             // handles this case, and causes any genuine format error to be
1390             // rethrown.
1391             String constant = negative ? ("-" + nm.substring(index))
1392                                        : nm.substring(index);
1393             result = parseInt(constant, radix);
1394         }
1395         return result;
1396     }
1397 
1398     /**
1399      * Compares two {@code Integer} objects numerically.
1400      *
1401      * @param   anotherInteger   the {@code Integer} to be compared.
1402      * @return  the value {@code 0} if this {@code Integer} is
1403      *          equal to the argument {@code Integer}; a value less than
1404      *          {@code 0} if this {@code Integer} is numerically less
1405      *          than the argument {@code Integer}; and a value greater
1406      *          than {@code 0} if this {@code Integer} is numerically
1407      *           greater than the argument {@code Integer} (signed
1408      *           comparison).
1409      * @since   1.2
1410      */
1411     public int compareTo(Integer anotherInteger) {
1412         return compare(this.value, anotherInteger.value);
1413     }
1414 
1415     /**
1416      * Compares two {@code int} values numerically.
1417      * The value returned is identical to what would be returned by:
1418      * <pre>
1419      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
1420      * </pre>
1421      *
1422      * @param  x the first {@code int} to compare
1423      * @param  y the second {@code int} to compare
1424      * @return the value {@code 0} if {@code x == y};
1425      *         a value less than {@code 0} if {@code x < y}; and
1426      *         a value greater than {@code 0} if {@code x > y}
1427      * @since 1.7
1428      */
1429     public static int compare(int x, int y) {
1430         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1431     }
1432 
1433     /**
1434      * Compares two {@code int} values numerically treating the values
1435      * as unsigned.
1436      *
1437      * @param  x the first {@code int} to compare
1438      * @param  y the second {@code int} to compare
1439      * @return the value {@code 0} if {@code x == y}; a value less
1440      *         than {@code 0} if {@code x < y} as unsigned values; and
1441      *         a value greater than {@code 0} if {@code x > y} as
1442      *         unsigned values
1443      * @since 1.8
1444      */
1445     @IntrinsicCandidate
1446     public static int compareUnsigned(int x, int y) {
1447         return compare(x + MIN_VALUE, y + MIN_VALUE);
1448     }
1449 
1450     /**
1451      * Converts the argument to a {@code long} by an unsigned
1452      * conversion.  In an unsigned conversion to a {@code long}, the
1453      * high-order 32 bits of the {@code long} are zero and the
1454      * low-order 32 bits are equal to the bits of the integer
1455      * argument.
1456      *
1457      * Consequently, zero and positive {@code int} values are mapped
1458      * to a numerically equal {@code long} value and negative {@code
1459      * int} values are mapped to a {@code long} value equal to the
1460      * input plus 2<sup>32</sup>.
1461      *
1462      * @param  x the value to convert to an unsigned {@code long}
1463      * @return the argument converted to {@code long} by an unsigned
1464      *         conversion
1465      * @since 1.8
1466      */
1467     public static long toUnsignedLong(int x) {
1468         return ((long) x) & 0xffffffffL;
1469     }
1470 
1471     /**
1472      * Returns the unsigned quotient of dividing the first argument by
1473      * the second where each argument and the result is interpreted as
1474      * an unsigned value.
1475      *
1476      * <p>Note that in two's complement arithmetic, the three other
1477      * basic arithmetic operations of add, subtract, and multiply are
1478      * bit-wise identical if the two operands are regarded as both
1479      * being signed or both being unsigned.  Therefore separate {@code
1480      * addUnsigned}, etc. methods are not provided.
1481      *
1482      * @param dividend the value to be divided
1483      * @param divisor the value doing the dividing
1484      * @return the unsigned quotient of the first argument divided by
1485      * the second argument
1486      * @see #remainderUnsigned
1487      * @since 1.8
1488      */
1489     @IntrinsicCandidate
1490     public static int divideUnsigned(int dividend, int divisor) {
1491         // In lieu of tricky code, for now just use long arithmetic.
1492         return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
1493     }
1494 
1495     /**
1496      * Returns the unsigned remainder from dividing the first argument
1497      * by the second where each argument and the result is interpreted
1498      * as an unsigned value.
1499      *
1500      * @param dividend the value to be divided
1501      * @param divisor the value doing the dividing
1502      * @return the unsigned remainder of the first argument divided by
1503      * the second argument
1504      * @see #divideUnsigned
1505      * @since 1.8
1506      */
1507     @IntrinsicCandidate
1508     public static int remainderUnsigned(int dividend, int divisor) {
1509         // In lieu of tricky code, for now just use long arithmetic.
1510         return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
1511     }
1512 
1513 
1514     // Bit twiddling
1515 
1516     /**
1517      * The number of bits used to represent an {@code int} value in two's
1518      * complement binary form.
1519      *
1520      * @since 1.5
1521      */
1522     @Native public static final int SIZE = 32;
1523 
1524     /**
1525      * The number of bytes used to represent an {@code int} value in two's
1526      * complement binary form.
1527      *
1528      * @since 1.8
1529      */
1530     public static final int BYTES = SIZE / Byte.SIZE;
1531 
1532     /**
1533      * Returns an {@code int} value with at most a single one-bit, in the
1534      * position of the highest-order ("leftmost") one-bit in the specified
1535      * {@code int} value.  Returns zero if the specified value has no
1536      * one-bits in its two's complement binary representation, that is, if it
1537      * is equal to zero.
1538      *
1539      * @param i the value whose highest one bit is to be computed
1540      * @return an {@code int} value with a single one-bit, in the position
1541      *     of the highest-order one-bit in the specified value, or zero if
1542      *     the specified value is itself equal to zero.
1543      * @since 1.5
1544      */
1545     public static int highestOneBit(int i) {
1546         return i & (MIN_VALUE >>> numberOfLeadingZeros(i));
1547     }
1548 
1549     /**
1550      * Returns an {@code int} value with at most a single one-bit, in the
1551      * position of the lowest-order ("rightmost") one-bit in the specified
1552      * {@code int} value.  Returns zero if the specified value has no
1553      * one-bits in its two's complement binary representation, that is, if it
1554      * is equal to zero.
1555      *
1556      * @param i the value whose lowest one bit is to be computed
1557      * @return an {@code int} value with a single one-bit, in the position
1558      *     of the lowest-order one-bit in the specified value, or zero if
1559      *     the specified value is itself equal to zero.
1560      * @since 1.5
1561      */
1562     public static int lowestOneBit(int i) {
1563         // HD, Section 2-1
1564         return i & -i;
1565     }
1566 
1567     /**
1568      * Returns the number of zero bits preceding the highest-order
1569      * ("leftmost") one-bit in the two's complement binary representation
1570      * of the specified {@code int} value.  Returns 32 if the
1571      * specified value has no one-bits in its two's complement representation,
1572      * in other words if it is equal to zero.
1573      *
1574      * <p>Note that this method is closely related to the logarithm base 2.
1575      * For all positive {@code int} values x:
1576      * <ul>
1577      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1578      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1579      * </ul>
1580      *
1581      * @param i the value whose number of leading zeros is to be computed
1582      * @return the number of zero bits preceding the highest-order
1583      *     ("leftmost") one-bit in the two's complement binary representation
1584      *     of the specified {@code int} value, or 32 if the value
1585      *     is equal to zero.
1586      * @since 1.5
1587      */
1588     @IntrinsicCandidate
1589     public static int numberOfLeadingZeros(int i) {
1590         // HD, Count leading 0's
1591         if (i <= 0)
1592             return i == 0 ? 32 : 0;
1593         int n = 31;
1594         if (i >= 1 << 16) { n -= 16; i >>>= 16; }
1595         if (i >= 1 <<  8) { n -=  8; i >>>=  8; }
1596         if (i >= 1 <<  4) { n -=  4; i >>>=  4; }
1597         if (i >= 1 <<  2) { n -=  2; i >>>=  2; }
1598         return n - (i >>> 1);
1599     }
1600 
1601     /**
1602      * Returns the number of zero bits following the lowest-order ("rightmost")
1603      * one-bit in the two's complement binary representation of the specified
1604      * {@code int} value.  Returns 32 if the specified value has no
1605      * one-bits in its two's complement representation, in other words if it is
1606      * equal to zero.
1607      *
1608      * @param i the value whose number of trailing zeros is to be computed
1609      * @return the number of zero bits following the lowest-order ("rightmost")
1610      *     one-bit in the two's complement binary representation of the
1611      *     specified {@code int} value, or 32 if the value is equal
1612      *     to zero.
1613      * @since 1.5
1614      */
1615     @IntrinsicCandidate
1616     public static int numberOfTrailingZeros(int i) {
1617         // HD, Count trailing 0's
1618         i = ~i & (i - 1);
1619         if (i <= 0) return i & 32;
1620         int n = 1;
1621         if (i > 1 << 16) { n += 16; i >>>= 16; }
1622         if (i > 1 <<  8) { n +=  8; i >>>=  8; }
1623         if (i > 1 <<  4) { n +=  4; i >>>=  4; }
1624         if (i > 1 <<  2) { n +=  2; i >>>=  2; }
1625         return n + (i >>> 1);
1626     }
1627 
1628     /**
1629      * Returns the number of one-bits in the two's complement binary
1630      * representation of the specified {@code int} value.  This function is
1631      * sometimes referred to as the <i>population count</i>.
1632      *
1633      * @param i the value whose bits are to be counted
1634      * @return the number of one-bits in the two's complement binary
1635      *     representation of the specified {@code int} value.
1636      * @since 1.5
1637      */
1638     @IntrinsicCandidate
1639     public static int bitCount(int i) {
1640         // HD, Figure 5-2
1641         i = i - ((i >>> 1) & 0x55555555);
1642         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1643         i = (i + (i >>> 4)) & 0x0f0f0f0f;
1644         i = i + (i >>> 8);
1645         i = i + (i >>> 16);
1646         return i & 0x3f;
1647     }
1648 
1649     /**
1650      * Returns the value obtained by rotating the two's complement binary
1651      * representation of the specified {@code int} value left by the
1652      * specified number of bits.  (Bits shifted out of the left hand, or
1653      * high-order, side reenter on the right, or low-order.)
1654      *
1655      * <p>Note that left rotation with a negative distance is equivalent to
1656      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1657      * distance)}.  Note also that rotation by any multiple of 32 is a
1658      * no-op, so all but the last five bits of the rotation distance can be
1659      * ignored, even if the distance is negative: {@code rotateLeft(val,
1660      * distance) == rotateLeft(val, distance & 0x1F)}.
1661      *
1662      * @param i the value whose bits are to be rotated left
1663      * @param distance the number of bit positions to rotate left
1664      * @return the value obtained by rotating the two's complement binary
1665      *     representation of the specified {@code int} value left by the
1666      *     specified number of bits.
1667      * @since 1.5
1668      */
1669     public static int rotateLeft(int i, int distance) {
1670         return (i << distance) | (i >>> -distance);
1671     }
1672 
1673     /**
1674      * Returns the value obtained by rotating the two's complement binary
1675      * representation of the specified {@code int} value right by the
1676      * specified number of bits.  (Bits shifted out of the right hand, or
1677      * low-order, side reenter on the left, or high-order.)
1678      *
1679      * <p>Note that right rotation with a negative distance is equivalent to
1680      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1681      * distance)}.  Note also that rotation by any multiple of 32 is a
1682      * no-op, so all but the last five bits of the rotation distance can be
1683      * ignored, even if the distance is negative: {@code rotateRight(val,
1684      * distance) == rotateRight(val, distance & 0x1F)}.
1685      *
1686      * @param i the value whose bits are to be rotated right
1687      * @param distance the number of bit positions to rotate right
1688      * @return the value obtained by rotating the two's complement binary
1689      *     representation of the specified {@code int} value right by the
1690      *     specified number of bits.
1691      * @since 1.5
1692      */
1693     public static int rotateRight(int i, int distance) {
1694         return (i >>> distance) | (i << -distance);
1695     }
1696 
1697     /**
1698      * Returns the value obtained by reversing the order of the bits in the
1699      * two's complement binary representation of the specified {@code int}
1700      * value.
1701      *
1702      * @param i the value to be reversed
1703      * @return the value obtained by reversing order of the bits in the
1704      *     specified {@code int} value.
1705      * @since 1.5
1706      */
1707     @IntrinsicCandidate
1708     public static int reverse(int i) {
1709         // HD, Figure 7-1
1710         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1711         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1712         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1713 
1714         return reverseBytes(i);
1715     }
1716 
1717     /**
1718      * Returns the value obtained by compressing the bits of the
1719      * specified {@code int} value, {@code i}, in accordance with
1720      * the specified bit mask.
1721      * <p>
1722      * For each one-bit value {@code mb} of the mask, from least
1723      * significant to most significant, the bit value of {@code i} at
1724      * the same bit location as {@code mb} is assigned to the compressed
1725      * value contiguously starting from the least significant bit location.
1726      * All the upper remaining bits of the compressed value are set
1727      * to zero.
1728      *
1729      * @apiNote
1730      * Consider the simple case of compressing the digits of a hexadecimal
1731      * value:
1732      * {@snippet lang="java" :
1733      * // Compressing drink to food
1734      * compress(0xCAFEBABE, 0xFF00FFF0) == 0xCABAB
1735      * }
1736      * Starting from the least significant hexadecimal digit at position 0
1737      * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits
1738      * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits
1739      * occur in the resulting compressed value contiguously from digit position
1740      * 0 in the same order.
1741      * <p>
1742      * The following identities all return {@code true} and are helpful to
1743      * understand the behaviour of {@code compress}:
1744      * {@snippet lang="java" :
1745      * // Returns 1 if the bit at position n is one
1746      * compress(x, 1 << n) == (x >> n & 1)
1747      *
1748      * // Logical shift right
1749      * compress(x, -1 << n) == x >>> n
1750      *
1751      * // Any bits not covered by the mask are ignored
1752      * compress(x, m) == compress(x & m, m)
1753      *
1754      * // Compressing a value by itself
1755      * compress(m, m) == (m == -1 || m == 0) ? m : (1 << bitCount(m)) - 1
1756      *
1757      * // Expanding then compressing with the same mask
1758      * compress(expand(x, m), m) == x & compress(m, m)
1759      * }
1760      * <p>
1761      * The Sheep And Goats (SAG) operation (see Hacker's Delight, Second Edition, section 7.7)
1762      * can be implemented as follows:
1763      * {@snippet lang="java" :
1764      * int compressLeft(int i, int mask) {
1765      *     // This implementation follows the description in Hacker's Delight which
1766      *     // is informative. A more optimal implementation is:
1767      *     //   Integer.compress(i, mask) << -Integer.bitCount(mask)
1768      *     return Integer.reverse(
1769      *         Integer.compress(Integer.reverse(i), Integer.reverse(mask)));
1770      * }
1771      *
1772      * int sag(int i, int mask) {
1773      *     return compressLeft(i, mask) | Integer.compress(i, ~mask);
1774      * }
1775      *
1776      * // Separate the sheep from the goats
1777      * sag(0xCAFEBABE, 0xFF00FFF0) == 0xCABABFEE
1778      * }
1779      *
1780      * @param i the value whose bits are to be compressed
1781      * @param mask the bit mask
1782      * @return the compressed value
1783      * @see #expand
1784      * @since 19
1785      */
1786     @IntrinsicCandidate
1787     public static int compress(int i, int mask) {
1788         // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract
1789 
1790         i = i & mask; // Clear irrelevant bits
1791         int maskCount = ~mask << 1; // Count 0's to right
1792 
1793         for (int j = 0; j < 5; j++) {
1794             // Parallel prefix
1795             // Mask prefix identifies bits of the mask that have an odd number of 0's to the right
1796             int maskPrefix = parallelSuffix(maskCount);
1797             // Bits to move
1798             int maskMove = maskPrefix & mask;
1799             // Compress mask
1800             mask = (mask ^ maskMove) | (maskMove >>> (1 << j));
1801             // Bits of i to be moved
1802             int t = i & maskMove;
1803             // Compress i
1804             i = (i ^ t) | (t >>> (1 << j));
1805             // Adjust the mask count by identifying bits that have 0 to the right
1806             maskCount = maskCount & ~maskPrefix;
1807         }
1808         return i;
1809     }
1810 
1811     /**
1812      * Returns the value obtained by expanding the bits of the
1813      * specified {@code int} value, {@code i}, in accordance with
1814      * the specified bit mask.
1815      * <p>
1816      * For each one-bit value {@code mb} of the mask, from least
1817      * significant to most significant, the next contiguous bit value
1818      * of {@code i} starting at the least significant bit is assigned
1819      * to the expanded value at the same bit location as {@code mb}.
1820      * All other remaining bits of the expanded value are set to zero.
1821      *
1822      * @apiNote
1823      * Consider the simple case of expanding the digits of a hexadecimal
1824      * value:
1825      * {@snippet lang="java" :
1826      * expand(0x0000CABAB, 0xFF00FFF0) == 0xCA00BAB0
1827      * }
1828      * Starting from the least significant hexadecimal digit at position 0
1829      * from the right, the mask {@code 0xFF00FFF0} selects the first five
1830      * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur
1831      * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7.
1832      * <p>
1833      * The following identities all return {@code true} and are helpful to
1834      * understand the behaviour of {@code expand}:
1835      * {@snippet lang="java" :
1836      * // Logically shift right the bit at position 0
1837      * expand(x, 1 << n) == (x & 1) << n
1838      *
1839      * // Logically shift right
1840      * expand(x, -1 << n) == x << n
1841      *
1842      * // Expanding all bits returns the mask
1843      * expand(-1, m) == m
1844      *
1845      * // Any bits not covered by the mask are ignored
1846      * expand(x, m) == expand(x, m) & m
1847      *
1848      * // Compressing then expanding with the same mask
1849      * expand(compress(x, m), m) == x & m
1850      * }
1851      * <p>
1852      * The select operation for determining the position of the one-bit with
1853      * index {@code n} in a {@code int} value can be implemented as follows:
1854      * {@snippet lang="java" :
1855      * int select(int i, int n) {
1856      *     // the one-bit in i (the mask) with index n
1857      *     int nthBit = Integer.expand(1 << n, i);
1858      *     // the bit position of the one-bit with index n
1859      *     return Integer.numberOfTrailingZeros(nthBit);
1860      * }
1861      *
1862      * // The one-bit with index 0 is at bit position 1
1863      * select(0b10101010_10101010, 0) == 1
1864      * // The one-bit with index 3 is at bit position 7
1865      * select(0b10101010_10101010, 3) == 7
1866      * }
1867      *
1868      * @param i the value whose bits are to be expanded
1869      * @param mask the bit mask
1870      * @return the expanded value
1871      * @see #compress
1872      * @since 19
1873      */
1874     @IntrinsicCandidate
1875     public static int expand(int i, int mask) {
1876         // Save original mask
1877         int originalMask = mask;
1878         // Count 0's to right
1879         int maskCount = ~mask << 1;
1880         int maskPrefix = parallelSuffix(maskCount);
1881         // Bits to move
1882         int maskMove1 = maskPrefix & mask;
1883         // Compress mask
1884         mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0));
1885         maskCount = maskCount & ~maskPrefix;
1886 
1887         maskPrefix = parallelSuffix(maskCount);
1888         // Bits to move
1889         int maskMove2 = maskPrefix & mask;
1890         // Compress mask
1891         mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1));
1892         maskCount = maskCount & ~maskPrefix;
1893 
1894         maskPrefix = parallelSuffix(maskCount);
1895         // Bits to move
1896         int maskMove3 = maskPrefix & mask;
1897         // Compress mask
1898         mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2));
1899         maskCount = maskCount & ~maskPrefix;
1900 
1901         maskPrefix = parallelSuffix(maskCount);
1902         // Bits to move
1903         int maskMove4 = maskPrefix & mask;
1904         // Compress mask
1905         mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3));
1906         maskCount = maskCount & ~maskPrefix;
1907 
1908         maskPrefix = parallelSuffix(maskCount);
1909         // Bits to move
1910         int maskMove5 = maskPrefix & mask;
1911 
1912         int t = i << (1 << 4);
1913         i = (i & ~maskMove5) | (t & maskMove5);
1914         t = i << (1 << 3);
1915         i = (i & ~maskMove4) | (t & maskMove4);
1916         t = i << (1 << 2);
1917         i = (i & ~maskMove3) | (t & maskMove3);
1918         t = i << (1 << 1);
1919         i = (i & ~maskMove2) | (t & maskMove2);
1920         t = i << (1 << 0);
1921         i = (i & ~maskMove1) | (t & maskMove1);
1922 
1923         // Clear irrelevant bits
1924         return i & originalMask;
1925     }
1926 
1927     @ForceInline
1928     private static int parallelSuffix(int maskCount) {
1929         int maskPrefix = maskCount ^ (maskCount << 1);
1930         maskPrefix = maskPrefix ^ (maskPrefix << 2);
1931         maskPrefix = maskPrefix ^ (maskPrefix << 4);
1932         maskPrefix = maskPrefix ^ (maskPrefix << 8);
1933         maskPrefix = maskPrefix ^ (maskPrefix << 16);
1934         return maskPrefix;
1935     }
1936 
1937     /**
1938      * Returns the signum function of the specified {@code int} value.  (The
1939      * return value is -1 if the specified value is negative; 0 if the
1940      * specified value is zero; and 1 if the specified value is positive.)
1941      *
1942      * @param i the value whose signum is to be computed
1943      * @return the signum function of the specified {@code int} value.
1944      * @since 1.5
1945      */
1946     public static int signum(int i) {
1947         // HD, Section 2-7
1948         return (i >> 31) | (-i >>> 31);
1949     }
1950 
1951     /**
1952      * Returns the value obtained by reversing the order of the bytes in the
1953      * two's complement representation of the specified {@code int} value.
1954      *
1955      * @param i the value whose bytes are to be reversed
1956      * @return the value obtained by reversing the bytes in the specified
1957      *     {@code int} value.
1958      * @since 1.5
1959      */
1960     @IntrinsicCandidate
1961     public static int reverseBytes(int i) {
1962         return (i << 24)            |
1963                ((i & 0xff00) << 8)  |
1964                ((i >>> 8) & 0xff00) |
1965                (i >>> 24);
1966     }
1967 
1968     /**
1969      * Adds two integers together as per the + operator.
1970      *
1971      * @param a the first operand
1972      * @param b the second operand
1973      * @return the sum of {@code a} and {@code b}
1974      * @see java.util.function.BinaryOperator
1975      * @since 1.8
1976      */
1977     public static int sum(int a, int b) {
1978         return a + b;
1979     }
1980 
1981     /**
1982      * Returns the greater of two {@code int} values
1983      * as if by calling {@link Math#max(int, int) Math.max}.
1984      *
1985      * @param a the first operand
1986      * @param b the second operand
1987      * @return the greater of {@code a} and {@code b}
1988      * @see java.util.function.BinaryOperator
1989      * @since 1.8
1990      */
1991     public static int max(int a, int b) {
1992         return Math.max(a, b);
1993     }
1994 
1995     /**
1996      * Returns the smaller of two {@code int} values
1997      * as if by calling {@link Math#min(int, int) Math.min}.
1998      *
1999      * @param a the first operand
2000      * @param b the second operand
2001      * @return the smaller of {@code a} and {@code b}
2002      * @see java.util.function.BinaryOperator
2003      * @since 1.8
2004      */
2005     public static int min(int a, int b) {
2006         return Math.min(a, b);
2007     }
2008 
2009     /**
2010      * Returns an {@link Optional} containing the nominal descriptor for this
2011      * instance, which is the instance itself.
2012      *
2013      * @return an {@link Optional} describing the {@linkplain Integer} instance
2014      * @since 12
2015      */
2016     @Override
2017     public Optional<Integer> describeConstable() {
2018         return Optional.of(this);
2019     }
2020 
2021     /**
2022      * Resolves this instance as a {@link ConstantDesc}, the result of which is
2023      * the instance itself.
2024      *
2025      * @param lookup ignored
2026      * @return the {@linkplain Integer} instance
2027      * @since 12
2028      */
2029     @Override
2030     public Integer resolveConstantDesc(MethodHandles.Lookup lookup) {
2031         return this;
2032     }
2033 
2034     /** use serialVersionUID from JDK 1.0.2 for interoperability */
2035     @java.io.Serial
2036     @Native private static final long serialVersionUID = 1360826667806852920L;
2037 }