rev 14560 : Merge

   1 /*
   2  * Copyright (c) 1994, 2013, 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 java.lang.annotation.Native;
  29 import java.util.Objects;
  30 import jdk.internal.HotSpotIntrinsicCandidate;
  31 import jdk.internal.misc.VM;
  32 
  33 import static java.lang.String.COMPACT_STRINGS;
  34 import static java.lang.String.LATIN1;
  35 import static java.lang.String.UTF16;
  36 
  37 /**
  38  * The {@code Integer} class wraps a value of the primitive type
  39  * {@code int} in an object. An object of type {@code Integer}
  40  * contains a single field whose type is {@code int}.
  41  *
  42  * <p>In addition, this class provides several methods for converting
  43  * an {@code int} to a {@code String} and a {@code String} to an
  44  * {@code int}, as well as other constants and methods useful when
  45  * dealing with an {@code int}.
  46  *
  47  * <p>Implementation note: The implementations of the "bit twiddling"
  48  * methods (such as {@link #highestOneBit(int) highestOneBit} and
  49  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
  50  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  51  * Delight</i>, (Addison Wesley, 2002).
  52  *
  53  * @author  Lee Boynton
  54  * @author  Arthur van Hoff
  55  * @author  Josh Bloch
  56  * @author  Joseph D. Darcy
  57  * @since 1.0
  58  */
  59 public final class Integer extends Number implements Comparable<Integer> {
  60     /**
  61      * A constant holding the minimum value an {@code int} can
  62      * have, -2<sup>31</sup>.
  63      */
  64     @Native public static final int   MIN_VALUE = 0x80000000;
  65 
  66     /**
  67      * A constant holding the maximum value an {@code int} can
  68      * have, 2<sup>31</sup>-1.
  69      */
  70     @Native public static final int   MAX_VALUE = 0x7fffffff;
  71 
  72     /**
  73      * The {@code Class} instance representing the primitive type
  74      * {@code int}.
  75      *
  76      * @since   1.1
  77      */
  78     @SuppressWarnings("unchecked")
  79     public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
  80 
  81     /**
  82      * All possible chars for representing a number as a String
  83      */
  84     static final char[] digits = {
  85         '0' , '1' , '2' , '3' , '4' , '5' ,
  86         '6' , '7' , '8' , '9' , 'a' , 'b' ,
  87         'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
  88         'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
  89         'o' , 'p' , 'q' , 'r' , 's' , 't' ,
  90         'u' , 'v' , 'w' , 'x' , 'y' , 'z'
  91     };
  92 
  93     /**
  94      * Returns a string representation of the first argument in the
  95      * radix specified by the second argument.
  96      *
  97      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
  98      * or larger than {@code Character.MAX_RADIX}, then the radix
  99      * {@code 10} is used instead.
 100      *
 101      * <p>If the first argument is negative, the first element of the
 102      * result is the ASCII minus character {@code '-'}
 103      * ({@code '\u005Cu002D'}). If the first argument is not
 104      * negative, no sign character appears in the result.
 105      *
 106      * <p>The remaining characters of the result represent the magnitude
 107      * of the first argument. If the magnitude is zero, it is
 108      * represented by a single zero character {@code '0'}
 109      * ({@code '\u005Cu0030'}); otherwise, the first character of
 110      * the representation of the magnitude will not be the zero
 111      * character.  The following ASCII characters are used as digits:
 112      *
 113      * <blockquote>
 114      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
 115      * </blockquote>
 116      *
 117      * These are {@code '\u005Cu0030'} through
 118      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 119      * {@code '\u005Cu007A'}. If {@code radix} is
 120      * <var>N</var>, then the first <var>N</var> of these characters
 121      * are used as radix-<var>N</var> digits in the order shown. Thus,
 122      * the digits for hexadecimal (radix 16) are
 123      * {@code 0123456789abcdef}. If uppercase letters are
 124      * desired, the {@link java.lang.String#toUpperCase()} method may
 125      * be called on the result:
 126      *
 127      * <blockquote>
 128      *  {@code Integer.toString(n, 16).toUpperCase()}
 129      * </blockquote>
 130      *
 131      * @param   i       an integer to be converted to a string.
 132      * @param   radix   the radix to use in the string representation.
 133      * @return  a string representation of the argument in the specified radix.
 134      * @see     java.lang.Character#MAX_RADIX
 135      * @see     java.lang.Character#MIN_RADIX
 136      */
 137     public static String toString(int i, int radix) {
 138         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 139             radix = 10;
 140 
 141         /* Use the faster version */
 142         if (radix == 10) {
 143             return toString(i);
 144         }
 145 
 146         if (COMPACT_STRINGS) {
 147             byte[] buf = new byte[33];
 148             boolean negative = (i < 0);
 149             int charPos = 32;
 150 
 151             if (!negative) {
 152                 i = -i;
 153             }
 154 
 155             while (i <= -radix) {
 156                 buf[charPos--] = (byte)digits[-(i % radix)];
 157                 i = i / radix;
 158             }
 159             buf[charPos] = (byte)digits[-i];
 160 
 161             if (negative) {
 162                 buf[--charPos] = '-';
 163             }
 164 
 165             return StringLatin1.newString(buf, charPos, (33 - charPos));
 166         }
 167         return toStringUTF16(i, radix);
 168     }
 169 
 170     private static String toStringUTF16(int i, int radix) {
 171         byte[] buf = new byte[33 * 2];
 172         boolean negative = (i < 0);
 173         int charPos = 32;
 174         if (!negative) {
 175             i = -i;
 176         }
 177         while (i <= -radix) {
 178             StringUTF16.putChar(buf, charPos--, digits[-(i % radix)]);
 179             i = i / radix;
 180         }
 181         StringUTF16.putChar(buf, charPos, digits[-i]);
 182 
 183         if (negative) {
 184             StringUTF16.putChar(buf, --charPos, '-');
 185         }
 186         return StringUTF16.newString(buf, charPos, (33 - charPos));
 187     }
 188 
 189     /**
 190      * Returns a string representation of the first argument as an
 191      * unsigned integer value in the radix specified by the second
 192      * argument.
 193      *
 194      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 195      * or larger than {@code Character.MAX_RADIX}, then the radix
 196      * {@code 10} is used instead.
 197      *
 198      * <p>Note that since the first argument is treated as an unsigned
 199      * value, no leading sign character is printed.
 200      *
 201      * <p>If the magnitude is zero, it is represented by a single zero
 202      * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
 203      * the first character of the representation of the magnitude will
 204      * not be the zero character.
 205      *
 206      * <p>The behavior of radixes and the characters used as digits
 207      * are the same as {@link #toString(int, int) toString}.
 208      *
 209      * @param   i       an integer to be converted to an unsigned string.
 210      * @param   radix   the radix to use in the string representation.
 211      * @return  an unsigned string representation of the argument in the specified radix.
 212      * @see     #toString(int, int)
 213      * @since 1.8
 214      */
 215     public static String toUnsignedString(int i, int radix) {
 216         return Long.toUnsignedString(toUnsignedLong(i), radix);
 217     }
 218 
 219     /**
 220      * Returns a string representation of the integer argument as an
 221      * unsigned integer in base&nbsp;16.
 222      *
 223      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 224      * if the argument is negative; otherwise, it is equal to the
 225      * argument.  This value is converted to a string of ASCII digits
 226      * in hexadecimal (base&nbsp;16) with no extra leading
 227      * {@code 0}s.
 228      *
 229      * <p>The value of the argument can be recovered from the returned
 230      * string {@code s} by calling {@link
 231      * Integer#parseUnsignedInt(String, int)
 232      * Integer.parseUnsignedInt(s, 16)}.
 233      *
 234      * <p>If the unsigned magnitude is zero, it is represented by a
 235      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 236      * otherwise, the first character of the representation of the
 237      * unsigned magnitude will not be the zero character. The
 238      * following characters are used as hexadecimal digits:
 239      *
 240      * <blockquote>
 241      *  {@code 0123456789abcdef}
 242      * </blockquote>
 243      *
 244      * These are the characters {@code '\u005Cu0030'} through
 245      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 246      * {@code '\u005Cu0066'}. If uppercase letters are
 247      * desired, the {@link java.lang.String#toUpperCase()} method may
 248      * be called on the result:
 249      *
 250      * <blockquote>
 251      *  {@code Integer.toHexString(n).toUpperCase()}
 252      * </blockquote>
 253      *
 254      * @param   i   an integer to be converted to a string.
 255      * @return  the string representation of the unsigned integer value
 256      *          represented by the argument in hexadecimal (base&nbsp;16).
 257      * @see #parseUnsignedInt(String, int)
 258      * @see #toUnsignedString(int, int)
 259      * @since   1.0.2
 260      */
 261     public static String toHexString(int i) {
 262         return toUnsignedString0(i, 4);
 263     }
 264 
 265     /**
 266      * Returns a string representation of the integer argument as an
 267      * unsigned integer in base&nbsp;8.
 268      *
 269      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 270      * if the argument is negative; otherwise, it is equal to the
 271      * argument.  This value is converted to a string of ASCII digits
 272      * in octal (base&nbsp;8) with no extra leading {@code 0}s.
 273      *
 274      * <p>The value of the argument can be recovered from the returned
 275      * string {@code s} by calling {@link
 276      * Integer#parseUnsignedInt(String, int)
 277      * Integer.parseUnsignedInt(s, 8)}.
 278      *
 279      * <p>If the unsigned magnitude is zero, it is represented by a
 280      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 281      * otherwise, the first character of the representation of the
 282      * unsigned magnitude will not be the zero character. The
 283      * following characters are used as octal digits:
 284      *
 285      * <blockquote>
 286      * {@code 01234567}
 287      * </blockquote>
 288      *
 289      * These are the characters {@code '\u005Cu0030'} through
 290      * {@code '\u005Cu0037'}.
 291      *
 292      * @param   i   an integer to be converted to a string.
 293      * @return  the string representation of the unsigned integer value
 294      *          represented by the argument in octal (base&nbsp;8).
 295      * @see #parseUnsignedInt(String, int)
 296      * @see #toUnsignedString(int, int)
 297      * @since   1.0.2
 298      */
 299     public static String toOctalString(int i) {
 300         return toUnsignedString0(i, 3);
 301     }
 302 
 303     /**
 304      * Returns a string representation of the integer argument as an
 305      * unsigned integer in base&nbsp;2.
 306      *
 307      * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 308      * if the argument is negative; otherwise it is equal to the
 309      * argument.  This value is converted to a string of ASCII digits
 310      * in binary (base&nbsp;2) with no extra leading {@code 0}s.
 311      *
 312      * <p>The value of the argument can be recovered from the returned
 313      * string {@code s} by calling {@link
 314      * Integer#parseUnsignedInt(String, int)
 315      * Integer.parseUnsignedInt(s, 2)}.
 316      *
 317      * <p>If the unsigned magnitude is zero, it is represented by a
 318      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 319      * otherwise, the first character of the representation of the
 320      * unsigned magnitude will not be the zero character. The
 321      * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
 322      * '1'} ({@code '\u005Cu0031'}) are used as binary digits.
 323      *
 324      * @param   i   an integer to be converted to a string.
 325      * @return  the string representation of the unsigned integer value
 326      *          represented by the argument in binary (base&nbsp;2).
 327      * @see #parseUnsignedInt(String, int)
 328      * @see #toUnsignedString(int, int)
 329      * @since   1.0.2
 330      */
 331     public static String toBinaryString(int i) {
 332         return toUnsignedString0(i, 1);
 333     }
 334 
 335     /**
 336      * Convert the integer to an unsigned number.
 337      */
 338     private static String toUnsignedString0(int val, int shift) {
 339         // assert shift > 0 && shift <=5 : "Illegal shift value";
 340         int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
 341         int chars = Math.max(((mag + (shift - 1)) / shift), 1);

 342         if (COMPACT_STRINGS) {
 343             byte[] buf = new byte[chars];
 344             formatUnsignedInt(val, shift, buf, 0, chars);
 345             return new String(buf, LATIN1);
 346         } else {
 347             byte[] buf = new byte[chars * 2];
 348             formatUnsignedIntUTF16(val, shift, buf, 0, chars);
 349             return new String(buf, UTF16);
 350         }
 351     }
 352 
 353     /**
 354      * Format an {@code int} (treated as unsigned) into a character buffer. If
 355      * {@code len} exceeds the formatted ASCII representation of {@code val},
 356      * {@code buf} will be padded with leading zeroes.
 357      *
 358      * @param val the unsigned int to format
 359      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 360      * @param buf the character buffer to write to
 361      * @param offset the offset in the destination buffer to start at
 362      * @param len the number of characters to write
 363      */
 364     static void formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
 365         // assert shift > 0 && shift <=5 : "Illegal shift value";
 366         // assert offset >= 0 && offset < buf.length : "illegal offset";
 367         // assert len > 0 && (offset + len) <= buf.length : "illegal length";
 368         int charPos = offset + len;
 369         int radix = 1 << shift;
 370         int mask = radix - 1;
 371         do {
 372             buf[--charPos] = Integer.digits[val & mask];
 373             val >>>= shift;
 374         } while (charPos > offset);
 375     }
 376 
 377     /** byte[]/LATIN1 version    */
 378     static void formatUnsignedInt(int val, int shift, byte[] buf, int offset, int len) {
 379         int charPos = offset + len;
 380         int radix = 1 << shift;
 381         int mask = radix - 1;
 382         do {
 383             buf[--charPos] = (byte)Integer.digits[val & mask];
 384             val >>>= shift;
 385         } while (charPos > offset);
 386     }
 387 
 388     /** byte[]/UTF16 version    */
 389     static void formatUnsignedIntUTF16(int val, int shift, byte[] buf, int offset, int len) {
 390         int charPos = offset + len;
 391         int radix = 1 << shift;
 392         int mask = radix - 1;
 393         do {
 394             StringUTF16.putChar(buf, --charPos, Integer.digits[val & mask]);
 395             val >>>= shift;
 396         } while (charPos > offset);
 397     }
 398 
 399     static final byte[] DigitTens = {
 400         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
 401         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
 402         '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
 403         '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
 404         '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
 405         '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
 406         '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
 407         '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
 408         '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
 409         '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
 410         } ;
 411 
 412     static final byte[] DigitOnes = {
 413         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 414         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 415         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 416         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 417         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 418         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 419         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 420         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 421         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 422         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
 423         } ;
 424 
 425 
 426     /**
 427      * Returns a {@code String} object representing the
 428      * specified integer. The argument is converted to signed decimal
 429      * representation and returned as a string, exactly as if the
 430      * argument and radix 10 were given as arguments to the {@link
 431      * #toString(int, int)} method.
 432      *
 433      * @param   i   an integer to be converted.
 434      * @return  a string representation of the argument in base&nbsp;10.
 435      */
 436     @HotSpotIntrinsicCandidate
 437     public static String toString(int i) {
 438         int size = stringSize(i);
 439         if (COMPACT_STRINGS) {
 440             byte[] buf = new byte[size];
 441             getChars(i, size, buf);
 442             return new String(buf, LATIN1);
 443         } else {
 444             byte[] buf = new byte[size * 2];
 445             getCharsUTF16(i, size, buf);
 446             return new String(buf, UTF16);
 447         }
 448     }
 449 
 450     /**
 451      * Returns a string representation of the argument as an unsigned
 452      * decimal value.
 453      *
 454      * The argument is converted to unsigned decimal representation
 455      * and returned as a string exactly as if the argument and radix
 456      * 10 were given as arguments to the {@link #toUnsignedString(int,
 457      * int)} method.
 458      *
 459      * @param   i  an integer to be converted to an unsigned string.
 460      * @return  an unsigned string representation of the argument.
 461      * @see     #toUnsignedString(int, int)
 462      * @since 1.8
 463      */
 464     public static String toUnsignedString(int i) {
 465         return Long.toString(toUnsignedLong(i));
 466     }
 467 
 468     /**
 469      * Places characters representing the integer i into the
 470      * character array buf. The characters are placed into
 471      * the buffer backwards starting with the least significant
 472      * digit at the specified index (exclusive), and working
 473      * backwards from there.
 474      *
 475      * @implNote This method converts positive inputs into negative
 476      * values, to cover the Integer.MIN_VALUE case. Converting otherwise
 477      * (negative to positive) will expose -Integer.MIN_VALUE that overflows
 478      * integer.
 479      *
 480      * @param i     value to convert
 481      * @param index next index, after the least significant digit
 482      * @param buf   target buffer, Latin1-encoded
 483      * @return index of the most significant digit or minus sign, if present
 484      */
 485     static int getChars(int i, int index, byte[] buf) {
 486         int q, r;
 487         int charPos = index;
 488 
 489         boolean negative = i < 0;
 490         if (!negative) {
 491             i = -i;
 492         }
 493 
 494         // Generate two digits per iteration
 495         while (i <= -100) {
 496             q = i / 100;
 497             r = (q * 100) - i;
 498             i = q;
 499             buf[--charPos] = DigitOnes[r];
 500             buf[--charPos] = DigitTens[r];
 501         }
 502 
 503         // We know there are at most two digits left at this point.
 504         q = i / 10;
 505         r = (q * 10) - i;
 506         buf[--charPos] = (byte)('0' + r);
 507 
 508         // Whatever left is the remaining digit.
 509         if (q < 0) {
 510             buf[--charPos] = (byte)('0' - q);
 511         }
 512 
 513         if (negative) {
 514             buf[--charPos] = (byte)'-';
 515         }
 516         return charPos;
 517     }
 518 
 519     /**
 520      * This is a variant of {@link #getChars(int, int, byte[])}, but for
 521      * UTF-16 coder.
 522      *
 523      * @param i     value to convert
 524      * @param index next index, after the least significant digit
 525      * @param buf   target buffer, UTF16-coded.
 526      * @return index of the most significant digit or minus sign, if present
 527      */
 528     static int getCharsUTF16(int i, int index, byte[] buf) {
 529         int q, r;
 530         int charPos = index;
 531 
 532         boolean negative = (i < 0);
 533         if (!negative) {
 534             i = -i;
 535         }
 536 
 537         // Get 2 digits/iteration using ints
 538         while (i <= -100) {
 539             q = i / 100;
 540             r = (q * 100) - i;
 541             i = q;
 542             StringUTF16.putChar(buf, --charPos, DigitOnes[r]);
 543             StringUTF16.putChar(buf, --charPos, DigitTens[r]);
 544         }
 545 
 546         // We know there are at most two digits left at this point.
 547         q = i / 10;
 548         r = (q * 10) - i;
 549         StringUTF16.putChar(buf, --charPos, '0' + r);
 550 
 551         // Whatever left is the remaining digit.
 552         if (q < 0) {
 553             StringUTF16.putChar(buf, --charPos, '0' - q);
 554         }
 555 
 556         if (negative) {
 557             StringUTF16.putChar(buf, --charPos, '-');
 558         }
 559         return charPos;
 560     }
 561 
 562     // Left here for compatibility reasons, see JDK-8143900.
 563     static final int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
 564                                       99999999, 999999999, Integer.MAX_VALUE };
 565 
 566     /**
 567      * Returns the string representation size for a given int value.
 568      *
 569      * @param x int value
 570      * @return string size
 571      *
 572      * @implNote There are other ways to compute this: e.g. binary search,
 573      * but values are biased heavily towards zero, and therefore linear search
 574      * wins. The iteration results are also routinely inlined in the generated
 575      * code after loop unrolling.
 576      */
 577     static int stringSize(int x) {
 578         int d = 1;
 579         if (x >= 0) {
 580             d = 0;
 581             x = -x;
 582         }
 583         int p = -10;
 584         for (int i = 1; i < 10; i++) {
 585             if (x > p)
 586                 return i + d;
 587             p = 10 * p;
 588         }
 589         return 10 + d;
 590     }
 591 
 592     /**
 593      * Parses the string argument as a signed integer in the radix
 594      * specified by the second argument. The characters in the string
 595      * must all be digits of the specified radix (as determined by
 596      * whether {@link java.lang.Character#digit(char, int)} returns a
 597      * nonnegative value), except that the first character may be an
 598      * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
 599      * indicate a negative value or an ASCII plus sign {@code '+'}
 600      * ({@code '\u005Cu002B'}) to indicate a positive value. The
 601      * resulting integer value is returned.
 602      *
 603      * <p>An exception of type {@code NumberFormatException} is
 604      * thrown if any of the following situations occurs:
 605      * <ul>
 606      * <li>The first argument is {@code null} or is a string of
 607      * length zero.
 608      *
 609      * <li>The radix is either smaller than
 610      * {@link java.lang.Character#MIN_RADIX} or
 611      * larger than {@link java.lang.Character#MAX_RADIX}.
 612      *
 613      * <li>Any character of the string is not a digit of the specified
 614      * radix, except that the first character may be a minus sign
 615      * {@code '-'} ({@code '\u005Cu002D'}) or plus sign
 616      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 617      * string is longer than length 1.
 618      *
 619      * <li>The value represented by the string is not a value of type
 620      * {@code int}.
 621      * </ul>
 622      *
 623      * <p>Examples:
 624      * <blockquote><pre>
 625      * parseInt("0", 10) returns 0
 626      * parseInt("473", 10) returns 473
 627      * parseInt("+42", 10) returns 42
 628      * parseInt("-0", 10) returns 0
 629      * parseInt("-FF", 16) returns -255
 630      * parseInt("1100110", 2) returns 102
 631      * parseInt("2147483647", 10) returns 2147483647
 632      * parseInt("-2147483648", 10) returns -2147483648
 633      * parseInt("2147483648", 10) throws a NumberFormatException
 634      * parseInt("99", 8) throws a NumberFormatException
 635      * parseInt("Kona", 10) throws a NumberFormatException
 636      * parseInt("Kona", 27) returns 411787
 637      * </pre></blockquote>
 638      *
 639      * @param      s   the {@code String} containing the integer
 640      *                  representation to be parsed
 641      * @param      radix   the radix to be used while parsing {@code s}.
 642      * @return     the integer represented by the string argument in the
 643      *             specified radix.
 644      * @exception  NumberFormatException if the {@code String}
 645      *             does not contain a parsable {@code int}.
 646      */
 647     public static int parseInt(String s, int radix)
 648                 throws NumberFormatException
 649     {
 650         /*
 651          * WARNING: This method may be invoked early during VM initialization
 652          * before IntegerCache is initialized. Care must be taken to not use
 653          * the valueOf method.
 654          */
 655 
 656         if (s == null) {
 657             throw new NumberFormatException("null");
 658         }
 659 
 660         if (radix < Character.MIN_RADIX) {
 661             throw new NumberFormatException("radix " + radix +
 662                                             " less than Character.MIN_RADIX");
 663         }
 664 
 665         if (radix > Character.MAX_RADIX) {
 666             throw new NumberFormatException("radix " + radix +
 667                                             " greater than Character.MAX_RADIX");
 668         }
 669 
 670         boolean negative = false;
 671         int i = 0, len = s.length();
 672         int limit = -Integer.MAX_VALUE;
 673 
 674         if (len > 0) {
 675             char firstChar = s.charAt(0);
 676             if (firstChar < '0') { // Possible leading "+" or "-"
 677                 if (firstChar == '-') {
 678                     negative = true;
 679                     limit = Integer.MIN_VALUE;
 680                 } else if (firstChar != '+') {
 681                     throw NumberFormatException.forInputString(s);
 682                 }
 683 
 684                 if (len == 1) { // Cannot have lone "+" or "-"
 685                     throw NumberFormatException.forInputString(s);
 686                 }
 687                 i++;
 688             }
 689             int multmin = limit / radix;
 690             int result = 0;
 691             while (i < len) {
 692                 // Accumulating negatively avoids surprises near MAX_VALUE
 693                 int digit = Character.digit(s.charAt(i++), radix);
 694                 if (digit < 0 || result < multmin) {
 695                     throw NumberFormatException.forInputString(s);
 696                 }
 697                 result *= radix;
 698                 if (result < limit + digit) {
 699                     throw NumberFormatException.forInputString(s);
 700                 }
 701                 result -= digit;
 702             }
 703             return negative ? result : -result;
 704         } else {
 705             throw NumberFormatException.forInputString(s);
 706         }
 707     }
 708 
 709     /**
 710      * Parses the {@link CharSequence} argument as a signed {@code int} in the
 711      * specified {@code radix}, beginning at the specified {@code beginIndex}
 712      * and extending to {@code endIndex - 1}.
 713      *
 714      * <p>The method does not take steps to guard against the
 715      * {@code CharSequence} being mutated while parsing.
 716      *
 717      * @param      s   the {@code CharSequence} containing the {@code int}
 718      *                  representation to be parsed
 719      * @param      beginIndex   the beginning index, inclusive.
 720      * @param      endIndex     the ending index, exclusive.
 721      * @param      radix   the radix to be used while parsing {@code s}.
 722      * @return     the signed {@code int} represented by the subsequence in
 723      *             the specified radix.
 724      * @throws     NullPointerException  if {@code s} is null.
 725      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 726      *             negative, or if {@code beginIndex} is greater than
 727      *             {@code endIndex} or if {@code endIndex} is greater than
 728      *             {@code s.length()}.
 729      * @throws     NumberFormatException  if the {@code CharSequence} does not
 730      *             contain a parsable {@code int} in the specified
 731      *             {@code radix}, or if {@code radix} is either smaller than
 732      *             {@link java.lang.Character#MIN_RADIX} or larger than
 733      *             {@link java.lang.Character#MAX_RADIX}.
 734      * @since  9
 735      */
 736     public static int parseInt(CharSequence s, int beginIndex, int endIndex, int radix)
 737                 throws NumberFormatException {
 738         s = Objects.requireNonNull(s);
 739 
 740         if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) {
 741             throw new IndexOutOfBoundsException();
 742         }
 743         if (radix < Character.MIN_RADIX) {
 744             throw new NumberFormatException("radix " + radix +
 745                                             " less than Character.MIN_RADIX");
 746         }
 747         if (radix > Character.MAX_RADIX) {
 748             throw new NumberFormatException("radix " + radix +
 749                                             " greater than Character.MAX_RADIX");
 750         }
 751 
 752         boolean negative = false;
 753         int i = beginIndex;
 754         int limit = -Integer.MAX_VALUE;
 755 
 756         if (i < endIndex) {
 757             char firstChar = s.charAt(i);
 758             if (firstChar < '0') { // Possible leading "+" or "-"
 759                 if (firstChar == '-') {
 760                     negative = true;
 761                     limit = Integer.MIN_VALUE;
 762                 } else if (firstChar != '+') {
 763                     throw NumberFormatException.forCharSequence(s, beginIndex,
 764                             endIndex, i);
 765                 }
 766                 i++;
 767                 if (i == endIndex) { // Cannot have lone "+" or "-"
 768                     throw NumberFormatException.forCharSequence(s, beginIndex,
 769                             endIndex, i);
 770                 }
 771             }
 772             int multmin = limit / radix;
 773             int result = 0;
 774             while (i < endIndex) {
 775                 // Accumulating negatively avoids surprises near MAX_VALUE
 776                 int digit = Character.digit(s.charAt(i), radix);
 777                 if (digit < 0 || result < multmin) {
 778                     throw NumberFormatException.forCharSequence(s, beginIndex,
 779                             endIndex, i);
 780                 }
 781                 result *= radix;
 782                 if (result < limit + digit) {
 783                     throw NumberFormatException.forCharSequence(s, beginIndex,
 784                             endIndex, i);
 785                 }
 786                 i++;
 787                 result -= digit;
 788             }
 789             return negative ? result : -result;
 790         } else {
 791             throw NumberFormatException.forInputString("");
 792         }
 793     }
 794 
 795     /**
 796      * Parses the string argument as a signed decimal integer. The
 797      * characters in the string must all be decimal digits, except
 798      * that the first character may be an ASCII minus sign {@code '-'}
 799      * ({@code '\u005Cu002D'}) to indicate a negative value or an
 800      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 801      * indicate a positive value. The resulting integer value is
 802      * returned, exactly as if the argument and the radix 10 were
 803      * given as arguments to the {@link #parseInt(java.lang.String,
 804      * int)} method.
 805      *
 806      * @param s    a {@code String} containing the {@code int}
 807      *             representation to be parsed
 808      * @return     the integer value represented by the argument in decimal.
 809      * @exception  NumberFormatException  if the string does not contain a
 810      *               parsable integer.
 811      */
 812     public static int parseInt(String s) throws NumberFormatException {
 813         return parseInt(s,10);
 814     }
 815 
 816     /**
 817      * Parses the string argument as an unsigned integer in the radix
 818      * specified by the second argument.  An unsigned integer maps the
 819      * values usually associated with negative numbers to positive
 820      * numbers larger than {@code MAX_VALUE}.
 821      *
 822      * The characters in the string must all be digits of the
 823      * specified radix (as determined by whether {@link
 824      * java.lang.Character#digit(char, int)} returns a nonnegative
 825      * value), except that the first character may be an ASCII plus
 826      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 827      * integer value is returned.
 828      *
 829      * <p>An exception of type {@code NumberFormatException} is
 830      * thrown if any of the following situations occurs:
 831      * <ul>
 832      * <li>The first argument is {@code null} or is a string of
 833      * length zero.
 834      *
 835      * <li>The radix is either smaller than
 836      * {@link java.lang.Character#MIN_RADIX} or
 837      * larger than {@link java.lang.Character#MAX_RADIX}.
 838      *
 839      * <li>Any character of the string is not a digit of the specified
 840      * radix, except that the first character may be a plus sign
 841      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 842      * string is longer than length 1.
 843      *
 844      * <li>The value represented by the string is larger than the
 845      * largest unsigned {@code int}, 2<sup>32</sup>-1.
 846      *
 847      * </ul>
 848      *
 849      *
 850      * @param      s   the {@code String} containing the unsigned integer
 851      *                  representation to be parsed
 852      * @param      radix   the radix to be used while parsing {@code s}.
 853      * @return     the integer represented by the string argument in the
 854      *             specified radix.
 855      * @throws     NumberFormatException if the {@code String}
 856      *             does not contain a parsable {@code int}.
 857      * @since 1.8
 858      */
 859     public static int parseUnsignedInt(String s, int radix)
 860                 throws NumberFormatException {
 861         if (s == null)  {
 862             throw new NumberFormatException("null");
 863         }
 864 
 865         int len = s.length();
 866         if (len > 0) {
 867             char firstChar = s.charAt(0);
 868             if (firstChar == '-') {
 869                 throw new
 870                     NumberFormatException(String.format("Illegal leading minus sign " +
 871                                                        "on unsigned string %s.", s));
 872             } else {
 873                 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
 874                     (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
 875                     return parseInt(s, radix);
 876                 } else {
 877                     long ell = Long.parseLong(s, radix);
 878                     if ((ell & 0xffff_ffff_0000_0000L) == 0) {
 879                         return (int) ell;
 880                     } else {
 881                         throw new
 882                             NumberFormatException(String.format("String value %s exceeds " +
 883                                                                 "range of unsigned int.", s));
 884                     }
 885                 }
 886             }
 887         } else {
 888             throw NumberFormatException.forInputString(s);
 889         }
 890     }
 891 
 892     /**
 893      * Parses the {@link CharSequence} argument as an unsigned {@code int} in
 894      * the specified {@code radix}, beginning at the specified
 895      * {@code beginIndex} and extending to {@code endIndex - 1}.
 896      *
 897      * <p>The method does not take steps to guard against the
 898      * {@code CharSequence} being mutated while parsing.
 899      *
 900      * @param      s   the {@code CharSequence} containing the unsigned
 901      *                 {@code int} representation to be parsed
 902      * @param      beginIndex   the beginning index, inclusive.
 903      * @param      endIndex     the ending index, exclusive.
 904      * @param      radix   the radix to be used while parsing {@code s}.
 905      * @return     the unsigned {@code int} represented by the subsequence in
 906      *             the specified radix.
 907      * @throws     NullPointerException  if {@code s} is null.
 908      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 909      *             negative, or if {@code beginIndex} is greater than
 910      *             {@code endIndex} or if {@code endIndex} is greater than
 911      *             {@code s.length()}.
 912      * @throws     NumberFormatException  if the {@code CharSequence} does not
 913      *             contain a parsable unsigned {@code int} in the specified
 914      *             {@code radix}, or if {@code radix} is either smaller than
 915      *             {@link java.lang.Character#MIN_RADIX} or larger than
 916      *             {@link java.lang.Character#MAX_RADIX}.
 917      * @since  9
 918      */
 919     public static int parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix)
 920                 throws NumberFormatException {
 921         s = Objects.requireNonNull(s);
 922 
 923         if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) {
 924             throw new IndexOutOfBoundsException();
 925         }
 926         int start = beginIndex, len = endIndex - beginIndex;
 927 
 928         if (len > 0) {
 929             char firstChar = s.charAt(start);
 930             if (firstChar == '-') {
 931                 throw new
 932                     NumberFormatException(String.format("Illegal leading minus sign " +
 933                                                        "on unsigned string %s.", s));
 934             } else {
 935                 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
 936                         (radix == 10 && len <= 9)) { // Integer.MAX_VALUE in base 10 is 10 digits
 937                     return parseInt(s, start, start + len, radix);
 938                 } else {
 939                     long ell = Long.parseLong(s, start, start + len, radix);
 940                     if ((ell & 0xffff_ffff_0000_0000L) == 0) {
 941                         return (int) ell;
 942                     } else {
 943                         throw new
 944                             NumberFormatException(String.format("String value %s exceeds " +
 945                                                                 "range of unsigned int.", s));
 946                     }
 947                 }
 948             }
 949         } else {
 950             throw new NumberFormatException("");
 951         }
 952     }
 953 
 954     /**
 955      * Parses the string argument as an unsigned decimal integer. The
 956      * characters in the string must all be decimal digits, except
 957      * that the first character may be an ASCII plus sign {@code
 958      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 959      * is returned, exactly as if the argument and the radix 10 were
 960      * given as arguments to the {@link
 961      * #parseUnsignedInt(java.lang.String, int)} method.
 962      *
 963      * @param s   a {@code String} containing the unsigned {@code int}
 964      *            representation to be parsed
 965      * @return    the unsigned integer value represented by the argument in decimal.
 966      * @throws    NumberFormatException  if the string does not contain a
 967      *            parsable unsigned integer.
 968      * @since 1.8
 969      */
 970     public static int parseUnsignedInt(String s) throws NumberFormatException {
 971         return parseUnsignedInt(s, 10);
 972     }
 973 
 974     /**
 975      * Returns an {@code Integer} object holding the value
 976      * extracted from the specified {@code String} when parsed
 977      * with the radix given by the second argument. The first argument
 978      * is interpreted as representing a signed integer in the radix
 979      * specified by the second argument, exactly as if the arguments
 980      * were given to the {@link #parseInt(java.lang.String, int)}
 981      * method. The result is an {@code Integer} object that
 982      * represents the integer value specified by the string.
 983      *
 984      * <p>In other words, this method returns an {@code Integer}
 985      * object equal to the value of:
 986      *
 987      * <blockquote>
 988      *  {@code new Integer(Integer.parseInt(s, radix))}
 989      * </blockquote>
 990      *
 991      * @param      s   the string to be parsed.
 992      * @param      radix the radix to be used in interpreting {@code s}
 993      * @return     an {@code Integer} object holding the value
 994      *             represented by the string argument in the specified
 995      *             radix.
 996      * @exception NumberFormatException if the {@code String}
 997      *            does not contain a parsable {@code int}.
 998      */
 999     public static Integer valueOf(String s, int radix) throws NumberFormatException {
1000         return Integer.valueOf(parseInt(s,radix));
1001     }
1002 
1003     /**
1004      * Returns an {@code Integer} object holding the
1005      * value of the specified {@code String}. The argument is
1006      * interpreted as representing a signed decimal integer, exactly
1007      * as if the argument were given to the {@link
1008      * #parseInt(java.lang.String)} method. The result is an
1009      * {@code Integer} object that represents the integer value
1010      * specified by the string.
1011      *
1012      * <p>In other words, this method returns an {@code Integer}
1013      * object equal to the value of:
1014      *
1015      * <blockquote>
1016      *  {@code new Integer(Integer.parseInt(s))}
1017      * </blockquote>
1018      *
1019      * @param      s   the string to be parsed.
1020      * @return     an {@code Integer} object holding the value
1021      *             represented by the string argument.
1022      * @exception  NumberFormatException  if the string cannot be parsed
1023      *             as an integer.
1024      */
1025     public static Integer valueOf(String s) throws NumberFormatException {
1026         return Integer.valueOf(parseInt(s, 10));
1027     }
1028 
1029     /**
1030      * Cache to support the object identity semantics of autoboxing for values between
1031      * -128 and 127 (inclusive) as required by JLS.
1032      *
1033      * The cache is initialized on first usage.  The size of the cache
1034      * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
1035      * During VM initialization, java.lang.Integer.IntegerCache.high property
1036      * may be set and saved in the private system properties in the
1037      * jdk.internal.misc.VM class.
1038      */
1039 
1040     private static class IntegerCache {
1041         static final int low = -128;
1042         static final int high;
1043         static final Integer cache[];
1044 
1045         static {
1046             // high value may be configured by property
1047             int h = 127;
1048             String integerCacheHighPropValue =
1049                 VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
1050             if (integerCacheHighPropValue != null) {
1051                 try {
1052                     int i = parseInt(integerCacheHighPropValue);
1053                     i = Math.max(i, 127);
1054                     // Maximum array size is Integer.MAX_VALUE
1055                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
1056                 } catch( NumberFormatException nfe) {
1057                     // If the property cannot be parsed into an int, ignore it.
1058                 }
1059             }
1060             high = h;
1061 
1062             cache = new Integer[(high - low) + 1];
1063             int j = low;
1064             for(int k = 0; k < cache.length; k++)
1065                 cache[k] = new Integer(j++);
1066 
1067             // range [-128, 127] must be interned (JLS7 5.1.7)
1068             assert IntegerCache.high >= 127;
1069         }
1070 
1071         private IntegerCache() {}
1072     }
1073 
1074     /**
1075      * Returns an {@code Integer} instance representing the specified
1076      * {@code int} value.  If a new {@code Integer} instance is not
1077      * required, this method should generally be used in preference to
1078      * the constructor {@link #Integer(int)}, as this method is likely
1079      * to yield significantly better space and time performance by
1080      * caching frequently requested values.
1081      *
1082      * This method will always cache values in the range -128 to 127,
1083      * inclusive, and may cache other values outside of this range.
1084      *
1085      * @param  i an {@code int} value.
1086      * @return an {@code Integer} instance representing {@code i}.
1087      * @since  1.5
1088      */
1089     @HotSpotIntrinsicCandidate
1090     public static Integer valueOf(int i) {
1091         if (i >= IntegerCache.low && i <= IntegerCache.high)
1092             return IntegerCache.cache[i + (-IntegerCache.low)];
1093         return new Integer(i);
1094     }
1095 
1096     /**
1097      * The value of the {@code Integer}.
1098      *
1099      * @serial
1100      */
1101     private final int value;
1102 
1103     /**
1104      * Constructs a newly allocated {@code Integer} object that
1105      * represents the specified {@code int} value.
1106      *
1107      * @param   value   the value to be represented by the
1108      *                  {@code Integer} object.
1109      */
1110     public Integer(int value) {
1111         this.value = value;
1112     }
1113 
1114     /**
1115      * Constructs a newly allocated {@code Integer} object that
1116      * represents the {@code int} value indicated by the
1117      * {@code String} parameter. The string is converted to an
1118      * {@code int} value in exactly the manner used by the
1119      * {@code parseInt} method for radix 10.
1120      *
1121      * @param      s   the {@code String} to be converted to an
1122      *                 {@code Integer}.
1123      * @exception  NumberFormatException  if the {@code String} does not
1124      *               contain a parsable integer.
1125      * @see        java.lang.Integer#parseInt(java.lang.String, int)
1126      */
1127     public Integer(String s) throws NumberFormatException {
1128         this.value = parseInt(s, 10);
1129     }
1130 
1131     /**
1132      * Returns the value of this {@code Integer} as a {@code byte}
1133      * after a narrowing primitive conversion.
1134      * @jls 5.1.3 Narrowing Primitive Conversions
1135      */
1136     public byte byteValue() {
1137         return (byte)value;
1138     }
1139 
1140     /**
1141      * Returns the value of this {@code Integer} as a {@code short}
1142      * after a narrowing primitive conversion.
1143      * @jls 5.1.3 Narrowing Primitive Conversions
1144      */
1145     public short shortValue() {
1146         return (short)value;
1147     }
1148 
1149     /**
1150      * Returns the value of this {@code Integer} as an
1151      * {@code int}.
1152      */
1153     @HotSpotIntrinsicCandidate
1154     public int intValue() {
1155         return value;
1156     }
1157 
1158     /**
1159      * Returns the value of this {@code Integer} as a {@code long}
1160      * after a widening primitive conversion.
1161      * @jls 5.1.2 Widening Primitive Conversions
1162      * @see Integer#toUnsignedLong(int)
1163      */
1164     public long longValue() {
1165         return (long)value;
1166     }
1167 
1168     /**
1169      * Returns the value of this {@code Integer} as a {@code float}
1170      * after a widening primitive conversion.
1171      * @jls 5.1.2 Widening Primitive Conversions
1172      */
1173     public float floatValue() {
1174         return (float)value;
1175     }
1176 
1177     /**
1178      * Returns the value of this {@code Integer} as a {@code double}
1179      * after a widening primitive conversion.
1180      * @jls 5.1.2 Widening Primitive Conversions
1181      */
1182     public double doubleValue() {
1183         return (double)value;
1184     }
1185 
1186     /**
1187      * Returns a {@code String} object representing this
1188      * {@code Integer}'s value. The value is converted to signed
1189      * decimal representation and returned as a string, exactly as if
1190      * the integer value were given as an argument to the {@link
1191      * java.lang.Integer#toString(int)} method.
1192      *
1193      * @return  a string representation of the value of this object in
1194      *          base&nbsp;10.
1195      */
1196     public String toString() {
1197         return toString(value);
1198     }
1199 
1200     /**
1201      * Returns a hash code for this {@code Integer}.
1202      *
1203      * @return  a hash code value for this object, equal to the
1204      *          primitive {@code int} value represented by this
1205      *          {@code Integer} object.
1206      */
1207     @Override
1208     public int hashCode() {
1209         return Integer.hashCode(value);
1210     }
1211 
1212     /**
1213      * Returns a hash code for a {@code int} value; compatible with
1214      * {@code Integer.hashCode()}.
1215      *
1216      * @param value the value to hash
1217      * @since 1.8
1218      *
1219      * @return a hash code value for a {@code int} value.
1220      */
1221     public static int hashCode(int value) {
1222         return value;
1223     }
1224 
1225     /**
1226      * Compares this object to the specified object.  The result is
1227      * {@code true} if and only if the argument is not
1228      * {@code null} and is an {@code Integer} object that
1229      * contains the same {@code int} value as this object.
1230      *
1231      * @param   obj   the object to compare with.
1232      * @return  {@code true} if the objects are the same;
1233      *          {@code false} otherwise.
1234      */
1235     public boolean equals(Object obj) {
1236         if (obj instanceof Integer) {
1237             return value == ((Integer)obj).intValue();
1238         }
1239         return false;
1240     }
1241 
1242     /**
1243      * Determines the integer value of the system property with the
1244      * specified name.
1245      *
1246      * <p>The first argument is treated as the name of a system
1247      * property.  System properties are accessible through the {@link
1248      * java.lang.System#getProperty(java.lang.String)} method. The
1249      * string value of this property is then interpreted as an integer
1250      * value using the grammar supported by {@link Integer#decode decode} and
1251      * an {@code Integer} object representing this value is returned.
1252      *
1253      * <p>If there is no property with the specified name, if the
1254      * specified name is empty or {@code null}, or if the property
1255      * does not have the correct numeric format, then {@code null} is
1256      * returned.
1257      *
1258      * <p>In other words, this method returns an {@code Integer}
1259      * object equal to the value of:
1260      *
1261      * <blockquote>
1262      *  {@code getInteger(nm, null)}
1263      * </blockquote>
1264      *
1265      * @param   nm   property name.
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     java.lang.System#getProperty(java.lang.String)
1270      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1271      */
1272     public static Integer getInteger(String nm) {
1273         return getInteger(nm, null);
1274     }
1275 
1276     /**
1277      * Determines the integer value of the system property with the
1278      * specified name.
1279      *
1280      * <p>The first argument is treated as the name of a system
1281      * property.  System properties are accessible through the {@link
1282      * java.lang.System#getProperty(java.lang.String)} method. The
1283      * string value of this property is then interpreted as an integer
1284      * value using the grammar supported by {@link Integer#decode decode} and
1285      * an {@code Integer} object representing this value is returned.
1286      *
1287      * <p>The second argument is the default value. An {@code Integer} object
1288      * that represents the value of the second argument is returned if there
1289      * is no property of the specified name, if the property does not have
1290      * the correct numeric format, or if the specified name is empty or
1291      * {@code null}.
1292      *
1293      * <p>In other words, this method returns an {@code Integer} object
1294      * equal to the value of:
1295      *
1296      * <blockquote>
1297      *  {@code getInteger(nm, new Integer(val))}
1298      * </blockquote>
1299      *
1300      * but in practice it may be implemented in a manner such as:
1301      *
1302      * <blockquote><pre>
1303      * Integer result = getInteger(nm, null);
1304      * return (result == null) ? new Integer(val) : result;
1305      * </pre></blockquote>
1306      *
1307      * to avoid the unnecessary allocation of an {@code Integer}
1308      * object when the default value is not needed.
1309      *
1310      * @param   nm   property name.
1311      * @param   val   default value.
1312      * @return  the {@code Integer} value of the property.
1313      * @throws  SecurityException for the same reasons as
1314      *          {@link System#getProperty(String) System.getProperty}
1315      * @see     java.lang.System#getProperty(java.lang.String)
1316      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1317      */
1318     public static Integer getInteger(String nm, int val) {
1319         Integer result = getInteger(nm, null);
1320         return (result == null) ? Integer.valueOf(val) : result;
1321     }
1322 
1323     /**
1324      * Returns the integer value of the system property with the
1325      * specified name.  The first argument is treated as the name of a
1326      * system property.  System properties are accessible through the
1327      * {@link java.lang.System#getProperty(java.lang.String)} method.
1328      * The string value of this property is then interpreted as an
1329      * integer value, as per the {@link Integer#decode decode} method,
1330      * and an {@code Integer} object representing this value is
1331      * returned; in summary:
1332      *
1333      * <ul><li>If the property value begins with the two ASCII characters
1334      *         {@code 0x} or the ASCII character {@code #}, not
1335      *      followed by a minus sign, then the rest of it is parsed as a
1336      *      hexadecimal integer exactly as by the method
1337      *      {@link #valueOf(java.lang.String, int)} with radix 16.
1338      * <li>If the property value begins with the ASCII character
1339      *     {@code 0} followed by another character, it is parsed as an
1340      *     octal integer exactly as by the method
1341      *     {@link #valueOf(java.lang.String, int)} with radix 8.
1342      * <li>Otherwise, the property value is parsed as a decimal integer
1343      * exactly as by the method {@link #valueOf(java.lang.String, int)}
1344      * with radix 10.
1345      * </ul>
1346      *
1347      * <p>The second argument is the default value. The default value is
1348      * returned if there is no property of the specified name, if the
1349      * property does not have the correct numeric format, or if the
1350      * specified name is empty or {@code null}.
1351      *
1352      * @param   nm   property name.
1353      * @param   val   default value.
1354      * @return  the {@code Integer} value of the property.
1355      * @throws  SecurityException for the same reasons as
1356      *          {@link System#getProperty(String) System.getProperty}
1357      * @see     System#getProperty(java.lang.String)
1358      * @see     System#getProperty(java.lang.String, java.lang.String)
1359      */
1360     public static Integer getInteger(String nm, Integer val) {
1361         String v = null;
1362         try {
1363             v = System.getProperty(nm);
1364         } catch (IllegalArgumentException | NullPointerException e) {
1365         }
1366         if (v != null) {
1367             try {
1368                 return Integer.decode(v);
1369             } catch (NumberFormatException e) {
1370             }
1371         }
1372         return val;
1373     }
1374 
1375     /**
1376      * Decodes a {@code String} into an {@code Integer}.
1377      * Accepts decimal, hexadecimal, and octal numbers given
1378      * by the following grammar:
1379      *
1380      * <blockquote>
1381      * <dl>
1382      * <dt><i>DecodableString:</i>
1383      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1384      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1385      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1386      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1387      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1388      *
1389      * <dt><i>Sign:</i>
1390      * <dd>{@code -}
1391      * <dd>{@code +}
1392      * </dl>
1393      * </blockquote>
1394      *
1395      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1396      * are as defined in section 3.10.1 of
1397      * <cite>The Java&trade; Language Specification</cite>,
1398      * except that underscores are not accepted between digits.
1399      *
1400      * <p>The sequence of characters following an optional
1401      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1402      * "{@code #}", or leading zero) is parsed as by the {@code
1403      * Integer.parseInt} method with the indicated radix (10, 16, or
1404      * 8).  This sequence of characters must represent a positive
1405      * value or a {@link NumberFormatException} will be thrown.  The
1406      * result is negated if first character of the specified {@code
1407      * String} is the minus sign.  No whitespace characters are
1408      * permitted in the {@code String}.
1409      *
1410      * @param     nm the {@code String} to decode.
1411      * @return    an {@code Integer} object holding the {@code int}
1412      *             value represented by {@code nm}
1413      * @exception NumberFormatException  if the {@code String} does not
1414      *            contain a parsable integer.
1415      * @see java.lang.Integer#parseInt(java.lang.String, int)
1416      */
1417     public static Integer decode(String nm) throws NumberFormatException {
1418         int radix = 10;
1419         int index = 0;
1420         boolean negative = false;
1421         Integer result;
1422 
1423         if (nm.length() == 0)
1424             throw new NumberFormatException("Zero length string");
1425         char firstChar = nm.charAt(0);
1426         // Handle sign, if present
1427         if (firstChar == '-') {
1428             negative = true;
1429             index++;
1430         } else if (firstChar == '+')
1431             index++;
1432 
1433         // Handle radix specifier, if present
1434         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1435             index += 2;
1436             radix = 16;
1437         }
1438         else if (nm.startsWith("#", index)) {
1439             index ++;
1440             radix = 16;
1441         }
1442         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1443             index ++;
1444             radix = 8;
1445         }
1446 
1447         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1448             throw new NumberFormatException("Sign character in wrong position");
1449 
1450         try {
1451             result = Integer.valueOf(nm.substring(index), radix);
1452             result = negative ? Integer.valueOf(-result.intValue()) : result;
1453         } catch (NumberFormatException e) {
1454             // If number is Integer.MIN_VALUE, we'll end up here. The next line
1455             // handles this case, and causes any genuine format error to be
1456             // rethrown.
1457             String constant = negative ? ("-" + nm.substring(index))
1458                                        : nm.substring(index);
1459             result = Integer.valueOf(constant, radix);
1460         }
1461         return result;
1462     }
1463 
1464     /**
1465      * Compares two {@code Integer} objects numerically.
1466      *
1467      * @param   anotherInteger   the {@code Integer} to be compared.
1468      * @return  the value {@code 0} if this {@code Integer} is
1469      *          equal to the argument {@code Integer}; a value less than
1470      *          {@code 0} if this {@code Integer} is numerically less
1471      *          than the argument {@code Integer}; and a value greater
1472      *          than {@code 0} if this {@code Integer} is numerically
1473      *           greater than the argument {@code Integer} (signed
1474      *           comparison).
1475      * @since   1.2
1476      */
1477     public int compareTo(Integer anotherInteger) {
1478         return compare(this.value, anotherInteger.value);
1479     }
1480 
1481     /**
1482      * Compares two {@code int} values numerically.
1483      * The value returned is identical to what would be returned by:
1484      * <pre>
1485      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
1486      * </pre>
1487      *
1488      * @param  x the first {@code int} to compare
1489      * @param  y the second {@code int} to compare
1490      * @return the value {@code 0} if {@code x == y};
1491      *         a value less than {@code 0} if {@code x < y}; and
1492      *         a value greater than {@code 0} if {@code x > y}
1493      * @since 1.7
1494      */
1495     public static int compare(int x, int y) {
1496         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1497     }
1498 
1499     /**
1500      * Compares two {@code int} values numerically treating the values
1501      * as unsigned.
1502      *
1503      * @param  x the first {@code int} to compare
1504      * @param  y the second {@code int} to compare
1505      * @return the value {@code 0} if {@code x == y}; a value less
1506      *         than {@code 0} if {@code x < y} as unsigned values; and
1507      *         a value greater than {@code 0} if {@code x > y} as
1508      *         unsigned values
1509      * @since 1.8
1510      */
1511     public static int compareUnsigned(int x, int y) {
1512         return compare(x + MIN_VALUE, y + MIN_VALUE);
1513     }
1514 
1515     /**
1516      * Converts the argument to a {@code long} by an unsigned
1517      * conversion.  In an unsigned conversion to a {@code long}, the
1518      * high-order 32 bits of the {@code long} are zero and the
1519      * low-order 32 bits are equal to the bits of the integer
1520      * argument.
1521      *
1522      * Consequently, zero and positive {@code int} values are mapped
1523      * to a numerically equal {@code long} value and negative {@code
1524      * int} values are mapped to a {@code long} value equal to the
1525      * input plus 2<sup>32</sup>.
1526      *
1527      * @param  x the value to convert to an unsigned {@code long}
1528      * @return the argument converted to {@code long} by an unsigned
1529      *         conversion
1530      * @since 1.8
1531      */
1532     public static long toUnsignedLong(int x) {
1533         return ((long) x) & 0xffffffffL;
1534     }
1535 
1536     /**
1537      * Returns the unsigned quotient of dividing the first argument by
1538      * the second where each argument and the result is interpreted as
1539      * an unsigned value.
1540      *
1541      * <p>Note that in two's complement arithmetic, the three other
1542      * basic arithmetic operations of add, subtract, and multiply are
1543      * bit-wise identical if the two operands are regarded as both
1544      * being signed or both being unsigned.  Therefore separate {@code
1545      * addUnsigned}, etc. methods are not provided.
1546      *
1547      * @param dividend the value to be divided
1548      * @param divisor the value doing the dividing
1549      * @return the unsigned quotient of the first argument divided by
1550      * the second argument
1551      * @see #remainderUnsigned
1552      * @since 1.8
1553      */
1554     public static int divideUnsigned(int dividend, int divisor) {
1555         // In lieu of tricky code, for now just use long arithmetic.
1556         return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
1557     }
1558 
1559     /**
1560      * Returns the unsigned remainder from dividing the first argument
1561      * by the second where each argument and the result is interpreted
1562      * as an unsigned value.
1563      *
1564      * @param dividend the value to be divided
1565      * @param divisor the value doing the dividing
1566      * @return the unsigned remainder of the first argument divided by
1567      * the second argument
1568      * @see #divideUnsigned
1569      * @since 1.8
1570      */
1571     public static int remainderUnsigned(int dividend, int divisor) {
1572         // In lieu of tricky code, for now just use long arithmetic.
1573         return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
1574     }
1575 
1576 
1577     // Bit twiddling
1578 
1579     /**
1580      * The number of bits used to represent an {@code int} value in two's
1581      * complement binary form.
1582      *
1583      * @since 1.5
1584      */
1585     @Native public static final int SIZE = 32;
1586 
1587     /**
1588      * The number of bytes used to represent a {@code int} value in two's
1589      * complement binary form.
1590      *
1591      * @since 1.8
1592      */
1593     public static final int BYTES = SIZE / Byte.SIZE;
1594 
1595     /**
1596      * Returns an {@code int} value with at most a single one-bit, in the
1597      * position of the highest-order ("leftmost") one-bit in the specified
1598      * {@code int} value.  Returns zero if the specified value has no
1599      * one-bits in its two's complement binary representation, that is, if it
1600      * is equal to zero.
1601      *
1602      * @param i the value whose highest one bit is to be computed
1603      * @return an {@code int} value with a single one-bit, in the position
1604      *     of the highest-order one-bit in the specified value, or zero if
1605      *     the specified value is itself equal to zero.
1606      * @since 1.5
1607      */
1608     public static int highestOneBit(int i) {
1609         // HD, Figure 3-1
1610         i |= (i >>  1);
1611         i |= (i >>  2);
1612         i |= (i >>  4);
1613         i |= (i >>  8);
1614         i |= (i >> 16);
1615         return i - (i >>> 1);
1616     }
1617 
1618     /**
1619      * Returns an {@code int} value with at most a single one-bit, in the
1620      * position of the lowest-order ("rightmost") one-bit in the specified
1621      * {@code int} value.  Returns zero if the specified value has no
1622      * one-bits in its two's complement binary representation, that is, if it
1623      * is equal to zero.
1624      *
1625      * @param i the value whose lowest one bit is to be computed
1626      * @return an {@code int} value with a single one-bit, in the position
1627      *     of the lowest-order one-bit in the specified value, or zero if
1628      *     the specified value is itself equal to zero.
1629      * @since 1.5
1630      */
1631     public static int lowestOneBit(int i) {
1632         // HD, Section 2-1
1633         return i & -i;
1634     }
1635 
1636     /**
1637      * Returns the number of zero bits preceding the highest-order
1638      * ("leftmost") one-bit in the two's complement binary representation
1639      * of the specified {@code int} value.  Returns 32 if the
1640      * specified value has no one-bits in its two's complement representation,
1641      * in other words if it is equal to zero.
1642      *
1643      * <p>Note that this method is closely related to the logarithm base 2.
1644      * For all positive {@code int} values x:
1645      * <ul>
1646      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1647      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1648      * </ul>
1649      *
1650      * @param i the value whose number of leading zeros is to be computed
1651      * @return the number of zero bits preceding the highest-order
1652      *     ("leftmost") one-bit in the two's complement binary representation
1653      *     of the specified {@code int} value, or 32 if the value
1654      *     is equal to zero.
1655      * @since 1.5
1656      */
1657     @HotSpotIntrinsicCandidate
1658     public static int numberOfLeadingZeros(int i) {
1659         // HD, Figure 5-6
1660         if (i == 0)
1661             return 32;
1662         int n = 1;
1663         if (i >>> 16 == 0) { n += 16; i <<= 16; }
1664         if (i >>> 24 == 0) { n +=  8; i <<=  8; }
1665         if (i >>> 28 == 0) { n +=  4; i <<=  4; }
1666         if (i >>> 30 == 0) { n +=  2; i <<=  2; }
1667         n -= i >>> 31;
1668         return n;
1669     }
1670 
1671     /**
1672      * Returns the number of zero bits following the lowest-order ("rightmost")
1673      * one-bit in the two's complement binary representation of the specified
1674      * {@code int} value.  Returns 32 if the specified value has no
1675      * one-bits in its two's complement representation, in other words if it is
1676      * equal to zero.
1677      *
1678      * @param i the value whose number of trailing zeros is to be computed
1679      * @return the number of zero bits following the lowest-order ("rightmost")
1680      *     one-bit in the two's complement binary representation of the
1681      *     specified {@code int} value, or 32 if the value is equal
1682      *     to zero.
1683      * @since 1.5
1684      */
1685     @HotSpotIntrinsicCandidate
1686     public static int numberOfTrailingZeros(int i) {
1687         // HD, Figure 5-14
1688         int y;
1689         if (i == 0) return 32;
1690         int n = 31;
1691         y = i <<16; if (y != 0) { n = n -16; i = y; }
1692         y = i << 8; if (y != 0) { n = n - 8; i = y; }
1693         y = i << 4; if (y != 0) { n = n - 4; i = y; }
1694         y = i << 2; if (y != 0) { n = n - 2; i = y; }
1695         return n - ((i << 1) >>> 31);
1696     }
1697 
1698     /**
1699      * Returns the number of one-bits in the two's complement binary
1700      * representation of the specified {@code int} value.  This function is
1701      * sometimes referred to as the <i>population count</i>.
1702      *
1703      * @param i the value whose bits are to be counted
1704      * @return the number of one-bits in the two's complement binary
1705      *     representation of the specified {@code int} value.
1706      * @since 1.5
1707      */
1708     @HotSpotIntrinsicCandidate
1709     public static int bitCount(int i) {
1710         // HD, Figure 5-2
1711         i = i - ((i >>> 1) & 0x55555555);
1712         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1713         i = (i + (i >>> 4)) & 0x0f0f0f0f;
1714         i = i + (i >>> 8);
1715         i = i + (i >>> 16);
1716         return i & 0x3f;
1717     }
1718 
1719     /**
1720      * Returns the value obtained by rotating the two's complement binary
1721      * representation of the specified {@code int} value left by the
1722      * specified number of bits.  (Bits shifted out of the left hand, or
1723      * high-order, side reenter on the right, or low-order.)
1724      *
1725      * <p>Note that left rotation with a negative distance is equivalent to
1726      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1727      * distance)}.  Note also that rotation by any multiple of 32 is a
1728      * no-op, so all but the last five bits of the rotation distance can be
1729      * ignored, even if the distance is negative: {@code rotateLeft(val,
1730      * distance) == rotateLeft(val, distance & 0x1F)}.
1731      *
1732      * @param i the value whose bits are to be rotated left
1733      * @param distance the number of bit positions to rotate left
1734      * @return the value obtained by rotating the two's complement binary
1735      *     representation of the specified {@code int} value left by the
1736      *     specified number of bits.
1737      * @since 1.5
1738      */
1739     public static int rotateLeft(int i, int distance) {
1740         return (i << distance) | (i >>> -distance);
1741     }
1742 
1743     /**
1744      * Returns the value obtained by rotating the two's complement binary
1745      * representation of the specified {@code int} value right by the
1746      * specified number of bits.  (Bits shifted out of the right hand, or
1747      * low-order, side reenter on the left, or high-order.)
1748      *
1749      * <p>Note that right rotation with a negative distance is equivalent to
1750      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1751      * distance)}.  Note also that rotation by any multiple of 32 is a
1752      * no-op, so all but the last five bits of the rotation distance can be
1753      * ignored, even if the distance is negative: {@code rotateRight(val,
1754      * distance) == rotateRight(val, distance & 0x1F)}.
1755      *
1756      * @param i the value whose bits are to be rotated right
1757      * @param distance the number of bit positions to rotate right
1758      * @return the value obtained by rotating the two's complement binary
1759      *     representation of the specified {@code int} value right by the
1760      *     specified number of bits.
1761      * @since 1.5
1762      */
1763     public static int rotateRight(int i, int distance) {
1764         return (i >>> distance) | (i << -distance);
1765     }
1766 
1767     /**
1768      * Returns the value obtained by reversing the order of the bits in the
1769      * two's complement binary representation of the specified {@code int}
1770      * value.
1771      *
1772      * @param i the value to be reversed
1773      * @return the value obtained by reversing order of the bits in the
1774      *     specified {@code int} value.
1775      * @since 1.5
1776      */
1777     public static int reverse(int i) {
1778         // HD, Figure 7-1
1779         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1780         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1781         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1782         i = (i << 24) | ((i & 0xff00) << 8) |
1783             ((i >>> 8) & 0xff00) | (i >>> 24);
1784         return i;
1785     }
1786 
1787     /**
1788      * Returns the signum function of the specified {@code int} value.  (The
1789      * return value is -1 if the specified value is negative; 0 if the
1790      * specified value is zero; and 1 if the specified value is positive.)
1791      *
1792      * @param i the value whose signum is to be computed
1793      * @return the signum function of the specified {@code int} value.
1794      * @since 1.5
1795      */
1796     public static int signum(int i) {
1797         // HD, Section 2-7
1798         return (i >> 31) | (-i >>> 31);
1799     }
1800 
1801     /**
1802      * Returns the value obtained by reversing the order of the bytes in the
1803      * two's complement representation of the specified {@code int} value.
1804      *
1805      * @param i the value whose bytes are to be reversed
1806      * @return the value obtained by reversing the bytes in the specified
1807      *     {@code int} value.
1808      * @since 1.5
1809      */
1810     @HotSpotIntrinsicCandidate
1811     public static int reverseBytes(int i) {
1812         return ((i >>> 24)           ) |
1813                ((i >>   8) &   0xFF00) |
1814                ((i <<   8) & 0xFF0000) |
1815                ((i << 24));
1816     }
1817 
1818     /**
1819      * Adds two integers together as per the + operator.
1820      *
1821      * @param a the first operand
1822      * @param b the second operand
1823      * @return the sum of {@code a} and {@code b}
1824      * @see java.util.function.BinaryOperator
1825      * @since 1.8
1826      */
1827     public static int sum(int a, int b) {
1828         return a + b;
1829     }
1830 
1831     /**
1832      * Returns the greater of two {@code int} values
1833      * as if by calling {@link Math#max(int, int) Math.max}.
1834      *
1835      * @param a the first operand
1836      * @param b the second operand
1837      * @return the greater of {@code a} and {@code b}
1838      * @see java.util.function.BinaryOperator
1839      * @since 1.8
1840      */
1841     public static int max(int a, int b) {
1842         return Math.max(a, b);
1843     }
1844 
1845     /**
1846      * Returns the smaller of two {@code int} values
1847      * as if by calling {@link Math#min(int, int) Math.min}.
1848      *
1849      * @param a the first operand
1850      * @param b the second operand
1851      * @return the smaller of {@code a} and {@code b}
1852      * @see java.util.function.BinaryOperator
1853      * @since 1.8
1854      */
1855     public static int min(int a, int b) {
1856         return Math.min(a, b);
1857     }
1858 
1859     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1860     @Native private static final long serialVersionUID = 1360826667806852920L;
1861 }
--- EOF ---