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