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