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