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 18package 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") 33public 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 */ 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 */ 101 public Integer(String string) throws NumberFormatException { 102 this(parseInt(string)); 103 } 104 105 @Override 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 */ 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 if lhs > rhs. 130 * @since 1.7 131 * @hide 1.7 132 */ 133 public static int compare(int lhs, int rhs) { 134 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); 135 } 136 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 minus sign "-" followed by a hexadecimal ("0x..." or "#..."), 145 * octal ("0..."), or decimal ("...") representation of an integer. 146 * 147 * @param string 148 * a string representation of an integer value. 149 * @return an {@code Integer} containing the value represented by 150 * {@code string}. 151 * @throws NumberFormatException 152 * if {@code string} cannot be parsed as an integer value. 153 */ 154 public static Integer decode(String string) throws NumberFormatException { 155 int length = string.length(), i = 0; 156 if (length == 0) { 157 throw invalidInt(string); 158 } 159 char firstDigit = string.charAt(i); 160 boolean negative = firstDigit == '-'; 161 if (negative) { 162 if (length == 1) { 163 throw invalidInt(string); 164 } 165 firstDigit = string.charAt(++i); 166 } 167 168 int base = 10; 169 if (firstDigit == '0') { 170 if (++i == length) { 171 return valueOf(0); 172 } 173 if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') { 174 if (++i == length) { 175 throw invalidInt(string); 176 } 177 base = 16; 178 } else { 179 base = 8; 180 } 181 } else if (firstDigit == '#') { 182 if (++i == length) { 183 throw invalidInt(string); 184 } 185 base = 16; 186 } 187 188 int result = parse(string, i, base, negative); 189 return valueOf(result); 190 } 191 192 @Override 193 public double doubleValue() { 194 return value; 195 } 196 197 /** 198 * Compares this instance with the specified object and indicates if they 199 * are equal. In order to be equal, {@code o} must be an instance of 200 * {@code Integer} and have the same integer value as this object. 201 * 202 * @param o 203 * the object to compare this integer with. 204 * @return {@code true} if the specified object is equal to this 205 * {@code Integer}; {@code false} otherwise. 206 */ 207 @Override 208 public boolean equals(Object o) { 209 return (o instanceof Integer) && (((Integer) o).value == value); 210 } 211 212 @Override 213 public float floatValue() { 214 return value; 215 } 216 217 /** 218 * Returns the {@code Integer} value of the system property identified by 219 * {@code string}. Returns {@code null} if {@code string} is {@code null} 220 * or empty, if the property can not be found or if its value can not be 221 * parsed as an integer. 222 * 223 * @param string 224 * the name of the requested system property. 225 * @return the requested property's value as an {@code Integer} or 226 * {@code null}. 227 */ 228 public static Integer getInteger(String string) { 229 if (string == null || string.length() == 0) { 230 return null; 231 } 232 String prop = System.getProperty(string); 233 if (prop == null) { 234 return null; 235 } 236 try { 237 return decode(prop); 238 } catch (NumberFormatException ex) { 239 return null; 240 } 241 } 242 243 /** 244 * Returns the {@code Integer} value of the system property identified by 245 * {@code string}. Returns the specified default value if {@code string} is 246 * {@code null} or empty, if the property can not be found or if its value 247 * can not be parsed as an integer. 248 * 249 * @param string 250 * the name of the requested system property. 251 * @param defaultValue 252 * the default value that is returned if there is no integer 253 * system property with the requested name. 254 * @return the requested property's value as an {@code Integer} or the 255 * default value. 256 */ 257 public static Integer getInteger(String string, int defaultValue) { 258 if (string == null || string.length() == 0) { 259 return valueOf(defaultValue); 260 } 261 String prop = System.getProperty(string); 262 if (prop == null) { 263 return valueOf(defaultValue); 264 } 265 try { 266 return decode(prop); 267 } catch (NumberFormatException ex) { 268 return valueOf(defaultValue); 269 } 270 } 271 272 /** 273 * Returns the {@code Integer} value of the system property identified by 274 * {@code string}. Returns the specified default value if {@code string} is 275 * {@code null} or empty, if the property can not be found or if its value 276 * can not be parsed as an integer. 277 * 278 * @param string 279 * the name of the requested system property. 280 * @param defaultValue 281 * the default value that is returned if there is no integer 282 * system property with the requested name. 283 * @return the requested property's value as an {@code Integer} or the 284 * default value. 285 */ 286 public static Integer getInteger(String string, Integer defaultValue) { 287 if (string == null || string.length() == 0) { 288 return defaultValue; 289 } 290 String prop = System.getProperty(string); 291 if (prop == null) { 292 return defaultValue; 293 } 294 try { 295 return decode(prop); 296 } catch (NumberFormatException ex) { 297 return defaultValue; 298 } 299 } 300 301 @Override 302 public int hashCode() { 303 return value; 304 } 305 306 /** 307 * Gets the primitive value of this int. 308 * 309 * @return this object's primitive value. 310 */ 311 @Override 312 public int intValue() { 313 return value; 314 } 315 316 @Override 317 public long longValue() { 318 return value; 319 } 320 321 /** 322 * Parses the specified string as a signed decimal integer value. The ASCII 323 * character \u002d ('-') is recognized as the minus sign. 324 * 325 * @param string 326 * the string representation of an integer value. 327 * @return the primitive integer value represented by {@code string}. 328 * @throws NumberFormatException 329 * if {@code string} cannot be parsed as an integer value. 330 */ 331 public static int parseInt(String string) throws NumberFormatException { 332 return parseInt(string, 10); 333 } 334 335 /** 336 * Parses the specified string as a signed integer value using the specified 337 * radix. The ASCII character \u002d ('-') is recognized as the minus sign. 338 * 339 * @param string 340 * the string representation of an integer value. 341 * @param radix 342 * the radix to use when parsing. 343 * @return the primitive integer value represented by {@code string} using 344 * {@code radix}. 345 * @throws NumberFormatException 346 * if {@code string} cannot be parsed as an integer value, 347 * or {@code radix < Character.MIN_RADIX || 348 * radix > Character.MAX_RADIX}. 349 */ 350 public static int parseInt(String string, int radix) throws NumberFormatException { 351 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 352 throw new NumberFormatException("Invalid radix: " + radix); 353 } 354 if (string == null) { 355 throw invalidInt(string); 356 } 357 int length = string.length(), i = 0; 358 if (length == 0) { 359 throw invalidInt(string); 360 } 361 boolean negative = string.charAt(i) == '-'; 362 if (negative && ++i == length) { 363 throw invalidInt(string); 364 } 365 366 return parse(string, i, radix, negative); 367 } 368 369 private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException { 370 int max = Integer.MIN_VALUE / radix; 371 int result = 0, length = string.length(); 372 while (offset < length) { 373 int digit = Character.digit(string.charAt(offset++), radix); 374 if (digit == -1) { 375 throw invalidInt(string); 376 } 377 if (max > result) { 378 throw invalidInt(string); 379 } 380 int next = result * radix - digit; 381 if (next > result) { 382 throw invalidInt(string); 383 } 384 result = next; 385 } 386 if (!negative) { 387 result = -result; 388 if (result < 0) { 389 throw invalidInt(string); 390 } 391 } 392 return result; 393 } 394 395 @Override 396 public short shortValue() { 397 return (short) value; 398 } 399 400 /** 401 * Converts the specified integer into its binary string representation. The 402 * returned string is a concatenation of '0' and '1' characters. 403 * 404 * @param i 405 * the integer to convert. 406 * @return the binary string representation of {@code i}. 407 */ 408 public static String toBinaryString(int i) { 409 return IntegralToString.intToBinaryString(i); 410 } 411 412 /** 413 * Converts the specified integer into its hexadecimal string 414 * representation. The returned string is a concatenation of characters from 415 * '0' to '9' and 'a' to 'f'. 416 * 417 * @param i 418 * the integer to convert. 419 * @return the hexadecimal string representation of {@code i}. 420 */ 421 public static String toHexString(int i) { 422 return IntegralToString.intToHexString(i, false, 0); 423 } 424 425 /** 426 * Converts the specified integer into its octal string representation. The 427 * returned string is a concatenation of characters from '0' to '7'. 428 * 429 * @param i 430 * the integer to convert. 431 * @return the octal string representation of {@code i}. 432 */ 433 public static String toOctalString(int i) { 434 return IntegralToString.intToOctalString(i); 435 } 436 437 @Override 438 public String toString() { 439 return Integer.toString(value); 440 } 441 442 /** 443 * Converts the specified integer into its decimal string representation. 444 * The returned string is a concatenation of a minus sign if the number is 445 * negative and characters from '0' to '9'. 446 * 447 * @param i 448 * the integer to convert. 449 * @return the decimal string representation of {@code i}. 450 */ 451 public static String toString(int i) { 452 return IntegralToString.intToString(i); 453 } 454 455 /** 456 * Converts the specified signed integer into a string representation based on the 457 * specified radix. The returned string is a concatenation of a minus sign 458 * if the number is negative and characters from '0' to '9' and 'a' to 'z', 459 * depending on the radix. If {@code radix} is not in the interval defined 460 * by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX} then 10 is 461 * used as the base for the conversion. 462 * 463 * <p>This method treats its argument as signed. If you want to convert an 464 * unsigned value to one of the common non-decimal bases, you may find 465 * {@link #toBinaryString}, {@code #toHexString}, or {@link #toOctalString} 466 * more convenient. 467 * 468 * @param i 469 * the signed integer to convert. 470 * @param radix 471 * the base to use for the conversion. 472 * @return the string representation of {@code i}. 473 */ 474 public static String toString(int i, int radix) { 475 return IntegralToString.intToString(i, radix); 476 } 477 478 /** 479 * Parses the specified string as a signed decimal integer value. 480 * 481 * @param string 482 * the string representation of an integer value. 483 * @return an {@code Integer} instance containing the integer value 484 * represented by {@code string}. 485 * @throws NumberFormatException 486 * if {@code string} cannot be parsed as an integer value. 487 * @see #parseInt(String) 488 */ 489 public static Integer valueOf(String string) throws NumberFormatException { 490 return valueOf(parseInt(string)); 491 } 492 493 /** 494 * Parses the specified string as a signed integer value using the specified 495 * radix. 496 * 497 * @param string 498 * the string representation of an integer value. 499 * @param radix 500 * the radix to use when parsing. 501 * @return an {@code Integer} instance containing the integer value 502 * represented by {@code string} using {@code radix}. 503 * @throws NumberFormatException 504 * if {@code string} cannot be parsed as an integer value, or 505 * {@code radix < Character.MIN_RADIX || 506 * radix > Character.MAX_RADIX}. 507 * @see #parseInt(String, int) 508 */ 509 public static Integer valueOf(String string, int radix) throws NumberFormatException { 510 return valueOf(parseInt(string, radix)); 511 } 512 513 /** 514 * Determines the highest (leftmost) bit of the specified integer that is 1 515 * and returns the bit mask value for that bit. This is also referred to as 516 * the Most Significant 1 Bit. Returns zero if the specified integer is 517 * zero. 518 * 519 * @param i 520 * the integer to examine. 521 * @return the bit mask indicating the highest 1 bit in {@code i}. 522 * @since 1.5 523 */ 524 public static int highestOneBit(int i) { 525 // Hacker's Delight, Figure 3-1 526 i |= (i >> 1); 527 i |= (i >> 2); 528 i |= (i >> 4); 529 i |= (i >> 8); 530 i |= (i >> 16); 531 return i - (i >>> 1); 532 } 533 534 /** 535 * Determines the lowest (rightmost) bit of the specified integer that is 1 536 * and returns the bit mask value for that bit. This is also referred 537 * to as the Least Significant 1 Bit. Returns zero if the specified integer 538 * is zero. 539 * 540 * @param i 541 * the integer to examine. 542 * @return the bit mask indicating the lowest 1 bit in {@code i}. 543 * @since 1.5 544 */ 545 public static int lowestOneBit(int i) { 546 return i & -i; 547 } 548 549 /** 550 * Determines the number of leading zeros in the specified integer prior to 551 * the {@link #highestOneBit(int) highest one bit}. 552 * 553 * @param i 554 * the integer to examine. 555 * @return the number of leading zeros in {@code i}. 556 * @since 1.5 557 */ 558 public static int numberOfLeadingZeros(int i) { 559 // Hacker's Delight, Figure 5-6 560 if (i <= 0) { 561 return (~i >> 26) & 32; 562 } 563 int n = 1; 564 if (i >> 16 == 0) { 565 n += 16; 566 i <<= 16; 567 } 568 if (i >> 24 == 0) { 569 n += 8; 570 i <<= 8; 571 } 572 if (i >> 28 == 0) { 573 n += 4; 574 i <<= 4; 575 } 576 if (i >> 30 == 0) { 577 n += 2; 578 i <<= 2; 579 } 580 return n - (i >>> 31); 581 } 582 583 /** 584 * Determines the number of trailing zeros in the specified integer after 585 * the {@link #lowestOneBit(int) lowest one bit}. 586 * 587 * @param i 588 * the integer to examine. 589 * @return the number of trailing zeros in {@code i}. 590 * @since 1.5 591 */ 592 public static int numberOfTrailingZeros(int i) { 593 return NTZ_TABLE[((i & -i) * 0x0450FBAF) >>> 26]; 594 } 595 596 /** 597 * Counts the number of 1 bits in the specified integer; this is also 598 * referred to as population count. 599 * 600 * @param i 601 * the integer to examine. 602 * @return the number of 1 bits in {@code i}. 603 * @since 1.5 604 */ 605 public static int bitCount(int i) { 606 // Hacker's Delight, Figure 5-2 607 i -= (i >> 1) & 0x55555555; 608 i = (i & 0x33333333) + ((i >> 2) & 0x33333333); 609 i = ((i >> 4) + i) & 0x0F0F0F0F; 610 i += i >> 8; 611 i += i >> 16; 612 return i & 0x0000003F; 613 } 614 615 /** 616 * Rotates the bits of the specified integer to the left by the specified 617 * number of bits. 618 * 619 * @param i 620 * the integer value to rotate left. 621 * @param distance 622 * the number of bits to rotate. 623 * @return the rotated value. 624 * @since 1.5 625 */ 626 public static int rotateLeft(int i, int distance) { 627 // Shift distances are mod 32 (JLS3 15.19), so we needn't mask -distance 628 return (i << distance) | (i >>> -distance); 629 } 630 631 /** 632 * Rotates the bits of the specified integer to the right by the specified 633 * number of bits. 634 * 635 * @param i 636 * the integer value to rotate right. 637 * @param distance 638 * the number of bits to rotate. 639 * @return the rotated value. 640 * @since 1.5 641 */ 642 public static int rotateRight(int i, int distance) { 643 // Shift distances are mod 32 (JLS3 15.19), so we needn't mask -distance 644 return (i >>> distance) | (i << -distance); 645 } 646 647 /** 648 * Reverses the order of the bytes of the specified integer. 649 * 650 * @param i 651 * the integer value for which to reverse the byte order. 652 * @return the reversed value. 653 * @since 1.5 654 */ 655 public static int reverseBytes(int i) { 656 // Hacker's Delight 7-1, with minor tweak from Veldmeijer 657 // http://graphics.stanford.edu/~seander/bithacks.html 658 i = ((i >>> 8) & 0x00FF00FF) | ((i & 0x00FF00FF) << 8); 659 return ( i >>> 16 ) | ( i << 16); 660 } 661 662 /** 663 * Reverses the order of the bits of the specified integer. 664 * 665 * @param i 666 * the integer value for which to reverse the bit order. 667 * @return the reversed value. 668 * @since 1.5 669 */ 670 public static int reverse(int i) { 671 // Hacker's Delight 7-1, with minor tweak from Veldmeijer 672 // http://graphics.stanford.edu/~seander/bithacks.html 673 i = ((i >>> 1) & 0x55555555) | ((i & 0x55555555) << 1); 674 i = ((i >>> 2) & 0x33333333) | ((i & 0x33333333) << 2); 675 i = ((i >>> 4) & 0x0F0F0F0F) | ((i & 0x0F0F0F0F) << 4); 676 i = ((i >>> 8) & 0x00FF00FF) | ((i & 0x00FF00FF) << 8); 677 return ((i >>> 16) ) | ((i ) << 16); 678 } 679 680 /** 681 * Returns the value of the {@code signum} function for the specified 682 * integer. 683 * 684 * @param i 685 * the integer value to check. 686 * @return -1 if {@code i} is negative, 1 if {@code i} is positive, 0 if 687 * {@code i} is zero. 688 * @since 1.5 689 */ 690 public static int signum(int i) { 691 return (i >> 31) | (-i >>> 31); // Hacker's delight 2-7 692 } 693 694 /** 695 * Returns a {@code Integer} instance for the specified integer value. 696 * <p> 697 * If it is not necessary to get a new {@code Integer} instance, it is 698 * recommended to use this method instead of the constructor, since it 699 * maintains a cache of instances which may result in better performance. 700 * 701 * @param i 702 * the integer value to store in the instance. 703 * @return a {@code Integer} instance containing {@code i}. 704 * @since 1.5 705 */ 706 public static Integer valueOf(int i) { 707 return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128]; 708 } 709 710 /** 711 * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing 712 */ 713 private static final Integer[] SMALL_VALUES = new Integer[256]; 714 715 static { 716 for (int i = -128; i < 128; i++) { 717 SMALL_VALUES[i + 128] = new Integer(i); 718 } 719 } 720} 721