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