1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package java.lang; 19 20 /** 21 * The wrapper for the primitive type {@code int}. 22 * <p> 23 * Implementation note: The "bit twiddling" methods in this class use techniques 24 * described in <a href="http://www.hackersdelight.org/">Henry S. Warren, 25 * Jr.'s Hacker's Delight, (Addison Wesley, 2002)</a> and <a href= 26 * "http://graphics.stanford.edu/~seander/bithacks.html">Sean Anderson's 27 * Bit Twiddling Hacks.</a> 28 * 29 * @see java.lang.Long 30 * @since 1.0 31 */ 32 @FindBugsSuppressWarnings("DM_NUMBER_CTOR") 33 public final class Integer extends Number implements Comparable<Integer> { 34 35 private static final long serialVersionUID = 1360826667806852920L; 36 37 /** 38 * The int value represented by this Integer 39 */ 40 private final int value; 41 42 /** 43 * Constant for the maximum {@code int} value, 2<sup>31</sup>-1. 44 */ 45 public static final int MAX_VALUE = 0x7FFFFFFF; 46 47 /** 48 * Constant for the minimum {@code int} value, -2<sup>31</sup>. 49 */ 50 public static final int MIN_VALUE = 0x80000000; 51 52 /** 53 * Constant for the number of bits needed to represent an {@code int} in 54 * two's complement form. 55 * 56 * @since 1.5 57 */ 58 public static final int SIZE = 32; 59 60 /** 61 * Table for Seal's algorithm for Number of Trailing Zeros. Hacker's Delight 62 * online, Figure 5-18 (http://www.hackersdelight.org/revisions.pdf) 63 * The entries whose value is -1 are never referenced. 64 */ 65 private static final byte[] NTZ_TABLE = { 66 32, 0, 1, 12, 2, 6, -1, 13, 3, -1, 7, -1, -1, -1, -1, 14, 67 10, 4, -1, -1, 8, -1, -1, 25, -1, -1, -1, -1, -1, 21, 27, 15, 68 31, 11, 5, -1, -1, -1, -1, -1, 9, -1, -1, 24, -1, -1, 20, 26, 69 30, -1, -1, -1, -1, 23, -1, 19, 29, -1, 22, 18, 28, 17, 16, -1 70 }; 71 72 /** 73 * The {@link Class} object that represents the primitive type {@code int}. 74 */ 75 @SuppressWarnings("unchecked") 76 public static final Class<Integer> TYPE 77 = (Class<Integer>) int[].class.getComponentType(); 78 // Note: Integer.TYPE can't be set to "int.class", since *that* is 79 // defined to be "java.lang.Integer.TYPE"; 80 81 /** 82 * Constructs a new {@code Integer} with the specified primitive integer 83 * value. 84 * 85 * @param value 86 * the primitive integer value to store in the new instance. 87 */ Integer(int value)88 public Integer(int value) { 89 this.value = value; 90 } 91 92 /** 93 * Constructs a new {@code Integer} from the specified string. 94 * 95 * @param string 96 * the string representation of an integer value. 97 * @throws NumberFormatException 98 * if {@code string} cannot be parsed as an integer value. 99 * @see #parseInt(String) 100 */ Integer(String string)101 public Integer(String string) throws NumberFormatException { 102 this(parseInt(string)); 103 } 104 105 @Override byteValue()106 public byte byteValue() { 107 return (byte) value; 108 } 109 110 /** 111 * Compares this object to the specified integer object to determine their 112 * relative order. 113 * 114 * @param object 115 * the integer object to compare this object to. 116 * @return a negative value if the value of this integer is less than the 117 * value of {@code object}; 0 if the value of this integer and the 118 * value of {@code object} are equal; a positive value if the value 119 * of this integer is greater than the value of {@code object}. 120 * @see java.lang.Comparable 121 * @since 1.2 122 */ compareTo(Integer object)123 public int compareTo(Integer object) { 124 return compare(value, object.value); 125 } 126 127 /** 128 * Compares two {@code int} values. 129 * @return 0 if lhs = rhs, less than 0 if lhs < rhs, and greater than 0 130 * if lhs > rhs. 131 * @since 1.7 132 */ compare(int lhs, int rhs)133 public static int compare(int lhs, int rhs) { 134 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); 135 } 136 invalidInt(String s)137 private static NumberFormatException invalidInt(String s) { 138 throw new NumberFormatException("Invalid int: \"" + s + "\""); 139 } 140 141 /** 142 * Parses the specified string and returns a {@code Integer} instance if the 143 * string can be decoded into an integer value. The string may be an 144 * optional sign character ("-" or "+") followed by a hexadecimal ("0x..." 145 * or "#..."), octal ("0..."), or decimal ("...") representation of an 146 * integer. 147 * 148 * @param string 149 * a string representation of an integer value. 150 * @return an {@code Integer} containing the value represented by 151 * {@code string}. 152 * @throws NumberFormatException 153 * if {@code string} cannot be parsed as an integer value. 154 */ decode(String string)155 public static Integer decode(String string) throws NumberFormatException { 156 int length = string.length(); 157 if (length == 0) { 158 throw invalidInt(string); 159 } 160 int i = 0; 161 char firstDigit = string.charAt(i); 162 boolean negative = firstDigit == '-'; 163 if (negative || firstDigit == '+') { 164 if (length == 1) { 165 throw invalidInt(string); 166 } 167 firstDigit = string.charAt(++i); 168 } 169 170 int base = 10; 171 if (firstDigit == '0') { 172 if (++i == length) { 173 return valueOf(0); 174 } 175 if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') { 176 if (++i == length) { 177 throw invalidInt(string); 178 } 179 base = 16; 180 } else { 181 base = 8; 182 } 183 } else if (firstDigit == '#') { 184 if (++i == length) { 185 throw invalidInt(string); 186 } 187 base = 16; 188 } 189 190 int result = parse(string, i, base, negative); 191 return valueOf(result); 192 } 193 194 @Override doubleValue()195 public double doubleValue() { 196 return value; 197 } 198 199 /** 200 * Compares this instance with the specified object and indicates if they 201 * are equal. In order to be equal, {@code o} must be an instance of 202 * {@code Integer} and have the same integer value as this object. 203 * 204 * @param o 205 * the object to compare this integer with. 206 * @return {@code true} if the specified object is equal to this 207 * {@code Integer}; {@code false} otherwise. 208 */ 209 @Override equals(Object o)210 public boolean equals(Object o) { 211 return (o instanceof Integer) && (((Integer) o).value == value); 212 } 213 214 @Override floatValue()215 public float floatValue() { 216 return value; 217 } 218 219 /** 220 * Returns the {@code Integer} value of the system property identified by 221 * {@code string}. Returns {@code null} if {@code string} is {@code null} 222 * or empty, if the property can not be found or if its value can not be 223 * parsed as an integer. 224 * 225 * @param string 226 * the name of the requested system property. 227 * @return the requested property's value as an {@code Integer} or 228 * {@code null}. 229 */ getInteger(String string)230 public static Integer getInteger(String string) { 231 if (string == null || string.length() == 0) { 232 return null; 233 } 234 String prop = System.getProperty(string); 235 if (prop == null) { 236 return null; 237 } 238 try { 239 return decode(prop); 240 } catch (NumberFormatException ex) { 241 return null; 242 } 243 } 244 245 /** 246 * Returns the {@code Integer} value of the system property identified by 247 * {@code string}. Returns the specified default value if {@code string} is 248 * {@code null} or empty, if the property can not be found or if its value 249 * can not be parsed as an integer. 250 * 251 * @param string 252 * the name of the requested system property. 253 * @param defaultValue 254 * the default value that is returned if there is no integer 255 * system property with the requested name. 256 * @return the requested property's value as an {@code Integer} or the 257 * default value. 258 */ getInteger(String string, int defaultValue)259 public static Integer getInteger(String string, int defaultValue) { 260 if (string == null || string.length() == 0) { 261 return valueOf(defaultValue); 262 } 263 String prop = System.getProperty(string); 264 if (prop == null) { 265 return valueOf(defaultValue); 266 } 267 try { 268 return decode(prop); 269 } catch (NumberFormatException ex) { 270 return valueOf(defaultValue); 271 } 272 } 273 274 /** 275 * Returns the {@code Integer} value of the system property identified by 276 * {@code string}. Returns the specified default value if {@code string} is 277 * {@code null} or empty, if the property can not be found or if its value 278 * can not be parsed as an integer. 279 * 280 * @param string 281 * the name of the requested system property. 282 * @param defaultValue 283 * the default value that is returned if there is no integer 284 * system property with the requested name. 285 * @return the requested property's value as an {@code Integer} or the 286 * default value. 287 */ getInteger(String string, Integer defaultValue)288 public static Integer getInteger(String string, Integer defaultValue) { 289 if (string == null || string.length() == 0) { 290 return defaultValue; 291 } 292 String prop = System.getProperty(string); 293 if (prop == null) { 294 return defaultValue; 295 } 296 try { 297 return decode(prop); 298 } catch (NumberFormatException ex) { 299 return defaultValue; 300 } 301 } 302 303 @Override hashCode()304 public int hashCode() { 305 return value; 306 } 307 308 /** 309 * Gets the primitive value of this int. 310 * 311 * @return this object's primitive value. 312 */ 313 @Override intValue()314 public int intValue() { 315 return value; 316 } 317 318 @Override longValue()319 public long longValue() { 320 return value; 321 } 322 323 /** 324 * Parses the specified string as a signed decimal integer value. The ASCII 325 * characters \u002d ('-') and \u002b ('+') are recognized as the minus and 326 * plus signs. 327 * @param string 328 * the string representation of an integer value. 329 * @return the primitive integer value represented by {@code string}. 330 * @throws NumberFormatException 331 * if {@code string} cannot be parsed as an integer value. 332 */ parseInt(String string)333 public static int parseInt(String string) throws NumberFormatException { 334 return parseInt(string, 10); 335 } 336 337 /** 338 * Parses the specified string as a signed integer value using the specified 339 * radix. The ASCII characters \u002d ('-') and \u002b ('+') are recognized 340 * as the minus and plus signs. 341 * 342 * @param string 343 * the string representation of an integer value. 344 * @param radix 345 * the radix to use when parsing. 346 * @return the primitive integer value represented by {@code string} using 347 * {@code radix}. 348 * @throws NumberFormatException 349 * if {@code string} cannot be parsed as an integer value, 350 * or {@code radix < Character.MIN_RADIX || 351 * radix > Character.MAX_RADIX}. 352 */ parseInt(String string, int radix)353 public static int parseInt(String string, int radix) throws NumberFormatException { 354 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 355 throw new NumberFormatException("Invalid radix: " + radix); 356 } 357 if (string == null || string.isEmpty()) { 358 throw invalidInt(string); 359 } 360 361 char firstChar = string.charAt(0); 362 int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0; 363 if (firstDigitIndex == string.length()) { 364 throw invalidInt(string); 365 } 366 367 return parse(string, firstDigitIndex, radix, firstChar == '-'); 368 } 369 370 /** 371 * Equivalent to {@code parsePositiveInt(string, 10)}. 372 * 373 * @see #parsePositiveInt(String, int) 374 * 375 * @hide 376 */ parsePositiveInt(String string)377 public static int parsePositiveInt(String string) throws NumberFormatException { 378 return parsePositiveInt(string, 10); 379 } 380 381 /** 382 * Parses the specified string as a positive integer value using the 383 * specified radix. 0 is considered a positive integer. 384 * <p> 385 * This method behaves the same as {@link #parseInt(String, int)} except 386 * that it disallows leading '+' and '-' characters. See that method for 387 * error conditions. 388 * 389 * @see #parseInt(String, int) 390 * 391 * @hide 392 */ parsePositiveInt(String string, int radix)393 public static int parsePositiveInt(String string, int radix) throws NumberFormatException { 394 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 395 throw new NumberFormatException("Invalid radix: " + radix); 396 } 397 if (string == null || string.length() == 0) { 398 throw invalidInt(string); 399 } 400 return parse(string, 0, radix, false); 401 } 402 parse(String string, int offset, int radix, boolean negative)403 private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException { 404 int max = Integer.MIN_VALUE / radix; 405 int result = 0; 406 int length = string.length(); 407 while (offset < length) { 408 int digit = Character.digit(string.charAt(offset++), radix); 409 if (digit == -1) { 410 throw invalidInt(string); 411 } 412 if (max > result) { 413 throw invalidInt(string); 414 } 415 int next = result * radix - digit; 416 if (next > result) { 417 throw invalidInt(string); 418 } 419 result = next; 420 } 421 if (!negative) { 422 result = -result; 423 if (result < 0) { 424 throw invalidInt(string); 425 } 426 } 427 return result; 428 } 429 430 @Override shortValue()431 public short shortValue() { 432 return (short) value; 433 } 434 435 /** 436 * Converts the specified integer into its binary string representation. The 437 * returned string is a concatenation of '0' and '1' characters. 438 * 439 * @param i 440 * the integer to convert. 441 * @return the binary string representation of {@code i}. 442 */ toBinaryString(int i)443 public static String toBinaryString(int i) { 444 return IntegralToString.intToBinaryString(i); 445 } 446 447 /** 448 * Converts the specified integer into its hexadecimal string 449 * representation. The returned string is a concatenation of characters from 450 * '0' to '9' and 'a' to 'f'. 451 * 452 * @param i 453 * the integer to convert. 454 * @return the hexadecimal string representation of {@code i}. 455 */ toHexString(int i)456 public static String toHexString(int i) { 457 return IntegralToString.intToHexString(i, false, 0); 458 } 459 460 /** 461 * Converts the specified integer into its octal string representation. The 462 * returned string is a concatenation of characters from '0' to '7'. 463 * 464 * @param i 465 * the integer to convert. 466 * @return the octal string representation of {@code i}. 467 */ toOctalString(int i)468 public static String toOctalString(int i) { 469 return IntegralToString.intToOctalString(i); 470 } 471 472 @Override toString()473 public String toString() { 474 return Integer.toString(value); 475 } 476 477 /** 478 * Converts the specified integer into its decimal string representation. 479 * The returned string is a concatenation of a minus sign if the number is 480 * negative and characters from '0' to '9'. 481 * 482 * @param i 483 * the integer to convert. 484 * @return the decimal string representation of {@code i}. 485 */ toString(int i)486 public static String toString(int i) { 487 return IntegralToString.intToString(i); 488 } 489 490 /** 491 * Converts the specified signed integer into a string representation based on the 492 * specified radix. The returned string is a concatenation of a minus sign 493 * if the number is negative and characters from '0' to '9' and 'a' to 'z', 494 * depending on the radix. If {@code radix} is not in the interval defined 495 * by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX} then 10 is 496 * used as the base for the conversion. 497 * 498 * <p>This method treats its argument as signed. If you want to convert an 499 * unsigned value to one of the common non-decimal bases, you may find 500 * {@link #toBinaryString}, {@code #toHexString}, or {@link #toOctalString} 501 * more convenient. 502 * 503 * @param i 504 * the signed integer to convert. 505 * @param radix 506 * the base to use for the conversion. 507 * @return the string representation of {@code i}. 508 */ toString(int i, int radix)509 public static String toString(int i, int radix) { 510 return IntegralToString.intToString(i, radix); 511 } 512 513 /** 514 * Parses the specified string as a signed decimal integer value. 515 * 516 * @param string 517 * the string representation of an integer value. 518 * @return an {@code Integer} instance containing the integer value 519 * represented by {@code string}. 520 * @throws NumberFormatException 521 * if {@code string} cannot be parsed as an integer value. 522 * @see #parseInt(String) 523 */ valueOf(String string)524 public static Integer valueOf(String string) throws NumberFormatException { 525 return valueOf(parseInt(string)); 526 } 527 528 /** 529 * Parses the specified string as a signed integer value using the specified 530 * radix. 531 * 532 * @param string 533 * the string representation of an integer value. 534 * @param radix 535 * the radix to use when parsing. 536 * @return an {@code Integer} instance containing the integer value 537 * represented by {@code string} using {@code radix}. 538 * @throws NumberFormatException 539 * if {@code string} cannot be parsed as an integer value, or 540 * {@code radix < Character.MIN_RADIX || 541 * radix > Character.MAX_RADIX}. 542 * @see #parseInt(String, int) 543 */ valueOf(String string, int radix)544 public static Integer valueOf(String string, int radix) throws NumberFormatException { 545 return valueOf(parseInt(string, radix)); 546 } 547 548 /** 549 * Determines the highest (leftmost) bit of the specified integer that is 1 550 * and returns the bit mask value for that bit. This is also referred to as 551 * the Most Significant 1 Bit. Returns zero if the specified integer is 552 * zero. 553 * 554 * @param i 555 * the integer to examine. 556 * @return the bit mask indicating the highest 1 bit in {@code i}. 557 * @since 1.5 558 */ highestOneBit(int i)559 public static int highestOneBit(int i) { 560 // Hacker's Delight, Figure 3-1 561 i |= (i >> 1); 562 i |= (i >> 2); 563 i |= (i >> 4); 564 i |= (i >> 8); 565 i |= (i >> 16); 566 return i - (i >>> 1); 567 } 568 569 /** 570 * Determines the lowest (rightmost) bit of the specified integer that is 1 571 * and returns the bit mask value for that bit. This is also referred 572 * to as the Least Significant 1 Bit. Returns zero if the specified integer 573 * is zero. 574 * 575 * @param i 576 * the integer to examine. 577 * @return the bit mask indicating the lowest 1 bit in {@code i}. 578 * @since 1.5 579 */ lowestOneBit(int i)580 public static int lowestOneBit(int i) { 581 return i & -i; 582 } 583 584 /** 585 * Determines the number of leading zeros in the specified integer prior to 586 * the {@link #highestOneBit(int) highest one bit}. 587 * 588 * @param i 589 * the integer to examine. 590 * @return the number of leading zeros in {@code i}. 591 * @since 1.5 592 */ numberOfLeadingZeros(int i)593 public static int numberOfLeadingZeros(int i) { 594 // Hacker's Delight, Figure 5-6 595 if (i <= 0) { 596 return (~i >> 26) & 32; 597 } 598 int n = 1; 599 if (i >> 16 == 0) { 600 n += 16; 601 i <<= 16; 602 } 603 if (i >> 24 == 0) { 604 n += 8; 605 i <<= 8; 606 } 607 if (i >> 28 == 0) { 608 n += 4; 609 i <<= 4; 610 } 611 if (i >> 30 == 0) { 612 n += 2; 613 i <<= 2; 614 } 615 return n - (i >>> 31); 616 } 617 618 /** 619 * Determines the number of trailing zeros in the specified integer after 620 * the {@link #lowestOneBit(int) lowest one bit}. 621 * 622 * @param i 623 * the integer to examine. 624 * @return the number of trailing zeros in {@code i}. 625 * @since 1.5 626 */ numberOfTrailingZeros(int i)627 public static int numberOfTrailingZeros(int i) { 628 return NTZ_TABLE[((i & -i) * 0x0450FBAF) >>> 26]; 629 } 630 631 /** 632 * Counts the number of 1 bits in the specified integer; this is also 633 * referred to as population count. 634 * 635 * @param i 636 * the integer to examine. 637 * @return the number of 1 bits in {@code i}. 638 * @since 1.5 639 */ bitCount(int i)640 public static int bitCount(int i) { 641 // Hacker's Delight, Figure 5-2 642 i -= (i >> 1) & 0x55555555; 643 i = (i & 0x33333333) + ((i >> 2) & 0x33333333); 644 i = ((i >> 4) + i) & 0x0F0F0F0F; 645 i += i >> 8; 646 i += i >> 16; 647 return i & 0x0000003F; 648 } 649 650 /** 651 * Rotates the bits of the specified integer to the left by the specified 652 * number of bits. 653 * 654 * @param i 655 * the integer value to rotate left. 656 * @param distance 657 * the number of bits to rotate. 658 * @return the rotated value. 659 * @since 1.5 660 */ rotateLeft(int i, int distance)661 public static int rotateLeft(int i, int distance) { 662 // Shift distances are mod 32 (JLS3 15.19), so we needn't mask -distance 663 return (i << distance) | (i >>> -distance); 664 } 665 666 /** 667 * Rotates the bits of the specified integer to the right by the specified 668 * number of bits. 669 * 670 * @param i 671 * the integer value to rotate right. 672 * @param distance 673 * the number of bits to rotate. 674 * @return the rotated value. 675 * @since 1.5 676 */ rotateRight(int i, int distance)677 public static int rotateRight(int i, int distance) { 678 // Shift distances are mod 32 (JLS3 15.19), so we needn't mask -distance 679 return (i >>> distance) | (i << -distance); 680 } 681 682 /** 683 * Reverses the order of the bytes of the specified integer. 684 * 685 * @param i 686 * the integer value for which to reverse the byte order. 687 * @return the reversed value. 688 * @since 1.5 689 */ reverseBytes(int i)690 public static int reverseBytes(int i) { 691 // Hacker's Delight 7-1, with minor tweak from Veldmeijer 692 // http://graphics.stanford.edu/~seander/bithacks.html 693 i = ((i >>> 8) & 0x00FF00FF) | ((i & 0x00FF00FF) << 8); 694 return ( i >>> 16 ) | ( i << 16); 695 } 696 697 /** 698 * Reverses the order of the bits of the specified integer. 699 * 700 * @param i 701 * the integer value for which to reverse the bit order. 702 * @return the reversed value. 703 * @since 1.5 704 */ reverse(int i)705 public static int reverse(int i) { 706 // Hacker's Delight 7-1, with minor tweak from Veldmeijer 707 // http://graphics.stanford.edu/~seander/bithacks.html 708 i = ((i >>> 1) & 0x55555555) | ((i & 0x55555555) << 1); 709 i = ((i >>> 2) & 0x33333333) | ((i & 0x33333333) << 2); 710 i = ((i >>> 4) & 0x0F0F0F0F) | ((i & 0x0F0F0F0F) << 4); 711 i = ((i >>> 8) & 0x00FF00FF) | ((i & 0x00FF00FF) << 8); 712 return ((i >>> 16) ) | ((i ) << 16); 713 } 714 715 /** 716 * Returns the value of the {@code signum} function for the specified 717 * integer. 718 * 719 * @param i 720 * the integer value to check. 721 * @return -1 if {@code i} is negative, 1 if {@code i} is positive, 0 if 722 * {@code i} is zero. 723 * @since 1.5 724 */ signum(int i)725 public static int signum(int i) { 726 return (i >> 31) | (-i >>> 31); // Hacker's delight 2-7 727 } 728 729 /** 730 * Returns a {@code Integer} instance for the specified integer value. 731 * <p> 732 * If it is not necessary to get a new {@code Integer} instance, it is 733 * recommended to use this method instead of the constructor, since it 734 * maintains a cache of instances which may result in better performance. 735 * 736 * @param i 737 * the integer value to store in the instance. 738 * @return a {@code Integer} instance containing {@code i}. 739 * @since 1.5 740 */ valueOf(int i)741 public static Integer valueOf(int i) { 742 return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128]; 743 } 744 745 /** 746 * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing 747 */ 748 private static final Integer[] SMALL_VALUES = new Integer[256]; 749 750 static { 751 for (int i = -128; i < 128; i++) { 752 SMALL_VALUES[i + 128] = new Integer(i); 753 } 754 } 755 } 756