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