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