1 /* 2 * Copyright (c) 1994, 2011, 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.util.Properties; 29 30 /** 31 * The {@code Integer} class wraps a value of the primitive type 32 * {@code int} in an object. An object of type {@code Integer} 33 * contains a single field whose type is {@code int}. 34 * 35 * <p>In addition, this class provides several methods for converting 36 * an {@code int} to a {@code String} and a {@code String} to an 37 * {@code int}, as well as other constants and methods useful when 38 * dealing with an {@code int}. 39 * 40 * <p>Implementation note: The implementations of the "bit twiddling" 41 * methods (such as {@link #highestOneBit(int) highestOneBit} and 42 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are 43 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 44 * Delight</i>, (Addison Wesley, 2002). 45 * 46 * @author Lee Boynton 47 * @author Arthur van Hoff 48 * @author Josh Bloch 49 * @author Joseph D. Darcy 50 * @since JDK1.0 51 */ 52 public final class Integer extends Number implements Comparable<Integer> { 53 /** 54 * A constant holding the minimum value an {@code int} can 55 * have, -2<sup>31</sup>. 56 */ 57 public static final int MIN_VALUE = 0x80000000; 58 59 /** 60 * A constant holding the maximum value an {@code int} can 61 * have, 2<sup>31</sup>-1. 62 */ 63 public static final int MAX_VALUE = 0x7fffffff; 64 65 /** 66 * The {@code Class} instance representing the primitive type 67 * {@code int}. 68 * 69 * @since JDK1.1 70 */ 71 @SuppressWarnings("unchecked") 72 public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int"); 73 74 /** 75 * All possible chars for representing a number as a String 76 */ 77 final static char[] digits = { 78 '0' , '1' , '2' , '3' , '4' , '5' , 79 '6' , '7' , '8' , '9' , 'a' , 'b' , 80 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 81 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 82 'o' , 'p' , 'q' , 'r' , 's' , 't' , 83 'u' , 'v' , 'w' , 'x' , 'y' , 'z' 84 }; 85 86 /** 87 * Returns a string representation of the first argument in the 88 * radix specified by the second argument. 89 * 90 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 91 * or larger than {@code Character.MAX_RADIX}, then the radix 92 * {@code 10} is used instead. 93 * 94 * <p>If the first argument is negative, the first element of the 95 * result is the ASCII minus character {@code '-'} 96 * (<code>'\u002D'</code>). If the first argument is not 97 * negative, no sign character appears in the result. 98 * 99 * <p>The remaining characters of the result represent the magnitude 100 * of the first argument. If the magnitude is zero, it is 101 * represented by a single zero character {@code '0'} 102 * (<code>'\u0030'</code>); otherwise, the first character of 103 * the representation of the magnitude will not be the zero 104 * character. The following ASCII characters are used as digits: 105 * 106 * <blockquote> 107 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 108 * </blockquote> 109 * 110 * These are <code>'\u0030'</code> through 111 * <code>'\u0039'</code> and <code>'\u0061'</code> through 112 * <code>'\u007A'</code>. If {@code radix} is 113 * <var>N</var>, then the first <var>N</var> of these characters 114 * are used as radix-<var>N</var> digits in the order shown. Thus, 115 * the digits for hexadecimal (radix 16) are 116 * {@code 0123456789abcdef}. If uppercase letters are 117 * desired, the {@link java.lang.String#toUpperCase()} method may 118 * be called on the result: 119 * 120 * <blockquote> 121 * {@code Integer.toString(n, 16).toUpperCase()} 122 * </blockquote> 123 * 124 * @param i an integer to be converted to a string. 125 * @param radix the radix to use in the string representation. 126 * @return a string representation of the argument in the specified radix. 127 * @see java.lang.Character#MAX_RADIX 128 * @see java.lang.Character#MIN_RADIX 129 */ 130 public static String toString(int i, int radix) { 131 132 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 133 radix = 10; 134 135 /* Use the faster version */ 136 if (radix == 10) { 137 return toString(i); 138 } 139 140 char buf[] = new char[33]; 141 boolean negative = (i < 0); 142 int charPos = 32; 143 144 if (!negative) { 145 i = -i; 146 } 147 148 while (i <= -radix) { 149 buf[charPos--] = digits[-(i % radix)]; 150 i = i / radix; 151 } 152 buf[charPos] = digits[-i]; 153 154 if (negative) { 155 buf[--charPos] = '-'; 156 } 157 158 return new String(buf, charPos, (33 - charPos)); 159 } 160 161 /** 162 * Returns a string representation of the integer argument as an 163 * unsigned integer in base 16. 164 * 165 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 166 * if the argument is negative; otherwise, it is equal to the 167 * argument. This value is converted to a string of ASCII digits 168 * in hexadecimal (base 16) with no extra leading 169 * {@code 0}s. If the unsigned magnitude is zero, it is 170 * represented by a single zero character {@code '0'} 171 * (<code>'\u0030'</code>); otherwise, the first character of 172 * the representation of the unsigned magnitude will not be the 173 * zero character. The following characters are used as 174 * hexadecimal digits: 175 * 176 * <blockquote> 177 * {@code 0123456789abcdef} 178 * </blockquote> 179 * 180 * These are the characters <code>'\u0030'</code> through 181 * <code>'\u0039'</code> and <code>'\u0061'</code> through 182 * <code>'\u0066'</code>. If uppercase letters are 183 * desired, the {@link java.lang.String#toUpperCase()} method may 184 * be called on the result: 185 * 186 * <blockquote> 187 * {@code Integer.toHexString(n).toUpperCase()} 188 * </blockquote> 189 * 190 * @param i an integer to be converted to a string. 191 * @return the string representation of the unsigned integer value 192 * represented by the argument in hexadecimal (base 16). 193 * @since JDK1.0.2 194 */ 195 public static String toHexString(int i) { 196 return toUnsignedString(i, 4); 197 } 198 199 /** 200 * Returns a string representation of the integer argument as an 201 * unsigned integer in base 8. 202 * 203 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 204 * if the argument is negative; otherwise, it is equal to the 205 * argument. This value is converted to a string of ASCII digits 206 * in octal (base 8) with no extra leading {@code 0}s. 207 * 208 * <p>If the unsigned magnitude is zero, it is represented by a 209 * single zero character {@code '0'} 210 * (<code>'\u0030'</code>); otherwise, the first character of 211 * the representation of the unsigned magnitude will not be the 212 * zero character. The following characters are used as octal 213 * digits: 214 * 215 * <blockquote> 216 * {@code 01234567} 217 * </blockquote> 218 * 219 * These are the characters <code>'\u0030'</code> through 220 * <code>'\u0037'</code>. 221 * 222 * @param i an integer to be converted to a string. 223 * @return the string representation of the unsigned integer value 224 * represented by the argument in octal (base 8). 225 * @since JDK1.0.2 226 */ 227 public static String toOctalString(int i) { 228 return toUnsignedString(i, 3); 229 } 230 231 /** 232 * Returns a string representation of the integer argument as an 233 * unsigned integer in base 2. 234 * 235 * <p>The unsigned integer value is the argument plus 2<sup>32</sup> 236 * if the argument is negative; otherwise it is equal to the 237 * argument. This value is converted to a string of ASCII digits 238 * in binary (base 2) with no extra leading {@code 0}s. 239 * If the unsigned magnitude is zero, it is represented by a 240 * single zero character {@code '0'} 241 * (<code>'\u0030'</code>); otherwise, the first character of 242 * the representation of the unsigned magnitude will not be the 243 * zero character. The characters {@code '0'} 244 * (<code>'\u0030'</code>) and {@code '1'} 245 * (<code>'\u0031'</code>) are used as binary digits. 246 * 247 * @param i an integer to be converted to a string. 248 * @return the string representation of the unsigned integer value 249 * represented by the argument in binary (base 2). 250 * @since JDK1.0.2 251 */ 252 public static String toBinaryString(int i) { 253 return toUnsignedString(i, 1); 254 } 255 256 /** 257 * Convert the integer to an unsigned number. 258 */ 259 private static String toUnsignedString(int i, int shift) { 260 char[] buf = new char[32]; 261 int charPos = 32; 262 int radix = 1 << shift; 263 int mask = radix - 1; 264 do { 265 buf[--charPos] = digits[i & mask]; 266 i >>>= shift; 267 } while (i != 0); 268 269 return new String(buf, charPos, (32 - charPos)); 270 } 271 272 273 final static char [] DigitTens = { 274 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 275 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 276 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 277 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 278 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 279 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 280 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 281 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 282 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 283 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 284 } ; 285 286 final static char [] DigitOnes = { 287 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 288 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 289 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 290 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 291 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 292 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 293 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 294 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 295 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 296 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 297 } ; 298 299 // I use the "invariant division by multiplication" trick to 300 // accelerate Integer.toString. In particular we want to 301 // avoid division by 10. 302 // 303 // The "trick" has roughly the same performance characteristics 304 // as the "classic" Integer.toString code on a non-JIT VM. 305 // The trick avoids .rem and .div calls but has a longer code 306 // path and is thus dominated by dispatch overhead. In the 307 // JIT case the dispatch overhead doesn't exist and the 308 // "trick" is considerably faster than the classic code. 309 // 310 // TODO-FIXME: convert (x * 52429) into the equiv shift-add 311 // sequence. 312 // 313 // RE: Division by Invariant Integers using Multiplication 314 // T Gralund, P Montgomery 315 // ACM PLDI 1994 316 // 317 318 /** 319 * Returns a {@code String} object representing the 320 * specified integer. The argument is converted to signed decimal 321 * representation and returned as a string, exactly as if the 322 * argument and radix 10 were given as arguments to the {@link 323 * #toString(int, int)} method. 324 * 325 * @param i an integer to be converted. 326 * @return a string representation of the argument in base 10. 327 */ 328 public static String toString(int i) { 329 if (i == Integer.MIN_VALUE) 330 return "-2147483648"; 331 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); 332 char[] buf = new char[size]; 333 getChars(i, size, buf); 334 return new String(0, size, buf); 335 } 336 337 /** 338 * Places characters representing the integer i into the 339 * character array buf. The characters are placed into 340 * the buffer backwards starting with the least significant 341 * digit at the specified index (exclusive), and working 342 * backwards from there. 343 * 344 * Will fail if i == Integer.MIN_VALUE 345 */ 346 static void getChars(int i, int index, char[] buf) { 347 int q, r; 348 int charPos = index; 349 char sign = 0; 350 351 if (i < 0) { 352 sign = '-'; 353 i = -i; 354 } 355 356 // Generate two digits per iteration 357 while (i >= 65536) { 358 q = i / 100; 359 // really: r = i - (q * 100); 360 r = i - ((q << 6) + (q << 5) + (q << 2)); 361 i = q; 362 buf [--charPos] = DigitOnes[r]; 363 buf [--charPos] = DigitTens[r]; 364 } 365 366 // Fall thru to fast mode for smaller numbers 367 // assert(i <= 65536, i); 368 for (;;) { 369 q = (i * 52429) >>> (16+3); 370 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... 371 buf [--charPos] = digits [r]; 372 i = q; 373 if (i == 0) break; 374 } 375 if (sign != 0) { 376 buf [--charPos] = sign; 377 } 378 } 379 380 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 381 99999999, 999999999, Integer.MAX_VALUE }; 382 383 // Requires positive x 384 static int stringSize(int x) { 385 for (int i=0; ; i++) 386 if (x <= sizeTable[i]) 387 return i+1; 388 } 389 390 /** 391 * Parses the string argument as a signed integer in the radix 392 * specified by the second argument. The characters in the string 393 * must all be digits of the specified radix (as determined by 394 * whether {@link java.lang.Character#digit(char, int)} returns a 395 * nonnegative value), except that the first character may be an 396 * ASCII minus sign {@code '-'} (<code>'\u002D'</code>) to 397 * indicate a negative value or an ASCII plus sign {@code '+'} 398 * (<code>'\u002B'</code>) to indicate a positive value. The 399 * resulting integer value is returned. 400 * 401 * <p>An exception of type {@code NumberFormatException} is 402 * thrown if any of the following situations occurs: 403 * <ul> 404 * <li>The first argument is {@code null} or is a string of 405 * length zero. 406 * 407 * <li>The radix is either smaller than 408 * {@link java.lang.Character#MIN_RADIX} or 409 * larger than {@link java.lang.Character#MAX_RADIX}. 410 * 411 * <li>Any character of the string is not a digit of the specified 412 * radix, except that the first character may be a minus sign 413 * {@code '-'} (<code>'\u002D'</code>) or plus sign 414 * {@code '+'} (<code>'\u002B'</code>) provided that the 415 * string is longer than length 1. 416 * 417 * <li>The value represented by the string is not a value of type 418 * {@code int}. 419 * </ul> 420 * 421 * <p>Examples: 422 * <blockquote><pre> 423 * parseInt("0", 10) returns 0 424 * parseInt("473", 10) returns 473 425 * parseInt("+42", 10) returns 42 426 * parseInt("-0", 10) returns 0 427 * parseInt("-FF", 16) returns -255 428 * parseInt("1100110", 2) returns 102 429 * parseInt("2147483647", 10) returns 2147483647 430 * parseInt("-2147483648", 10) returns -2147483648 431 * parseInt("2147483648", 10) throws a NumberFormatException 432 * parseInt("99", 8) throws a NumberFormatException 433 * parseInt("Kona", 10) throws a NumberFormatException 434 * parseInt("Kona", 27) returns 411787 435 * </pre></blockquote> 436 * 437 * @param s the {@code String} containing the integer 438 * representation to be parsed 439 * @param radix the radix to be used while parsing {@code s}. 440 * @return the integer represented by the string argument in the 441 * specified radix. 442 * @exception NumberFormatException if the {@code String} 443 * does not contain a parsable {@code int}. 444 */ 445 public static int parseInt(String s, int radix) 446 throws NumberFormatException 447 { 448 /* 449 * WARNING: This method may be invoked early during VM initialization 450 * before IntegerCache is initialized. Care must be taken to not use 451 * the valueOf method. 452 */ 453 454 if (s == null) { 455 throw new NumberFormatException("null"); 456 } 457 458 if (radix < Character.MIN_RADIX) { 459 throw new NumberFormatException("radix " + radix + 460 " less than Character.MIN_RADIX"); 461 } 462 463 if (radix > Character.MAX_RADIX) { 464 throw new NumberFormatException("radix " + radix + 465 " greater than Character.MAX_RADIX"); 466 } 467 468 int result = 0; 469 boolean negative = false; 470 int i = 0, len = s.length(); 471 int limit = -Integer.MAX_VALUE; 472 int multmin; 473 int digit; 474 475 if (len > 0) { 476 char firstChar = s.charAt(0); 477 if (firstChar < '0') { // Possible leading "+" or "-" 478 if (firstChar == '-') { 479 negative = true; 480 limit = Integer.MIN_VALUE; 481 } else if (firstChar != '+') 482 throw NumberFormatException.forInputString(s); 483 484 if (len == 1) // Cannot have lone "+" or "-" 485 throw NumberFormatException.forInputString(s); 486 i++; 487 } 488 multmin = limit / radix; 489 while (i < len) { 490 // Accumulating negatively avoids surprises near MAX_VALUE 491 digit = Character.digit(s.charAt(i++),radix); 492 if (digit < 0) { 493 throw NumberFormatException.forInputString(s); 494 } 495 if (result < multmin) { 496 throw NumberFormatException.forInputString(s); 497 } 498 result *= radix; 499 if (result < limit + digit) { 500 throw NumberFormatException.forInputString(s); 501 } 502 result -= digit; 503 } 504 } else { 505 throw NumberFormatException.forInputString(s); 506 } 507 return negative ? result : -result; 508 } 509 510 /** 511 * Parses the string argument as a signed decimal integer. The 512 * characters in the string must all be decimal digits, except 513 * that the first character may be an ASCII minus sign {@code '-'} 514 * (<code>'\u002D'</code>) to indicate a negative value or an 515 * ASCII plus sign {@code '+'} (<code>'\u002B'</code>) to 516 * indicate a positive value. The resulting integer value is 517 * returned, exactly as if the argument and the radix 10 were 518 * given as arguments to the {@link #parseInt(java.lang.String, 519 * int)} method. 520 * 521 * @param s a {@code String} containing the {@code int} 522 * representation to be parsed 523 * @return the integer value represented by the argument in decimal. 524 * @exception NumberFormatException if the string does not contain a 525 * parsable integer. 526 */ 527 public static int parseInt(String s) throws NumberFormatException { 528 return parseInt(s,10); 529 } 530 531 /** 532 * Returns an {@code Integer} object holding the value 533 * extracted from the specified {@code String} when parsed 534 * with the radix given by the second argument. The first argument 535 * is interpreted as representing a signed integer in the radix 536 * specified by the second argument, exactly as if the arguments 537 * were given to the {@link #parseInt(java.lang.String, int)} 538 * method. The result is an {@code Integer} object that 539 * represents the integer value specified by the string. 540 * 541 * <p>In other words, this method returns an {@code Integer} 542 * object equal to the value of: 543 * 544 * <blockquote> 545 * {@code new Integer(Integer.parseInt(s, radix))} 546 * </blockquote> 547 * 548 * @param s the string to be parsed. 549 * @param radix the radix to be used in interpreting {@code s} 550 * @return an {@code Integer} object holding the value 551 * represented by the string argument in the specified 552 * radix. 553 * @exception NumberFormatException if the {@code String} 554 * does not contain a parsable {@code int}. 555 */ 556 public static Integer valueOf(String s, int radix) throws NumberFormatException { 557 return Integer.valueOf(parseInt(s,radix)); 558 } 559 560 /** 561 * Returns an {@code Integer} object holding the 562 * value of the specified {@code String}. The argument is 563 * interpreted as representing a signed decimal integer, exactly 564 * as if the argument were given to the {@link 565 * #parseInt(java.lang.String)} method. The result is an 566 * {@code Integer} object that represents the integer value 567 * specified by the string. 568 * 569 * <p>In other words, this method returns an {@code Integer} 570 * object equal to the value of: 571 * 572 * <blockquote> 573 * {@code new Integer(Integer.parseInt(s))} 574 * </blockquote> 575 * 576 * @param s the string to be parsed. 577 * @return an {@code Integer} object holding the value 578 * represented by the string argument. 579 * @exception NumberFormatException if the string cannot be parsed 580 * as an integer. 581 */ 582 public static Integer valueOf(String s) throws NumberFormatException { 583 return Integer.valueOf(parseInt(s, 10)); 584 } 585 586 /** 587 * Cache to support the object identity semantics of autoboxing for values between 588 * -128 and 127 (inclusive) as required by JLS. 589 * 590 * The cache is initialized on first usage. The size of the cache 591 * may be controlled by the -XX:AutoBoxCacheMax=<size> option. 592 * During VM initialization, java.lang.Integer.IntegerCache.high property 593 * may be set and saved in the private system properties in the 594 * sun.misc.VM class. 595 */ 596 597 private static class IntegerCache { 598 static final int low = -128; 599 static final int high; 600 static final Integer cache[]; 601 602 static { 603 // high value may be configured by property 604 int h = 127; 605 String integerCacheHighPropValue = 606 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 607 if (integerCacheHighPropValue != null) { 608 int i = parseInt(integerCacheHighPropValue); 609 i = Math.max(i, 127); 610 // Maximum array size is Integer.MAX_VALUE 611 h = Math.min(i, Integer.MAX_VALUE - (-low)); 612 } 613 high = h; 614 615 cache = new Integer[(high - low) + 1]; 616 int j = low; 617 for(int k = 0; k < cache.length; k++) 618 cache[k] = new Integer(j++); 619 } 620 621 private IntegerCache() {} 622 } 623 624 /** 625 * Returns an {@code Integer} instance representing the specified 626 * {@code int} value. If a new {@code Integer} instance is not 627 * required, this method should generally be used in preference to 628 * the constructor {@link #Integer(int)}, as this method is likely 629 * to yield significantly better space and time performance by 630 * caching frequently requested values. 631 * 632 * This method will always cache values in the range -128 to 127, 633 * inclusive, and may cache other values outside of this range. 634 * 635 * @param i an {@code int} value. 636 * @return an {@code Integer} instance representing {@code i}. 637 * @since 1.5 638 */ 639 public static Integer valueOf(int i) { 640 assert IntegerCache.high >= 127; 641 if (i >= IntegerCache.low && i <= IntegerCache.high) 642 return IntegerCache.cache[i + (-IntegerCache.low)]; 643 return new Integer(i); 644 } 645 646 /** 647 * The value of the {@code Integer}. 648 * 649 * @serial 650 */ 651 private final int value; 652 653 /** 654 * Constructs a newly allocated {@code Integer} object that 655 * represents the specified {@code int} value. 656 * 657 * @param value the value to be represented by the 658 * {@code Integer} object. 659 */ 660 public Integer(int value) { 661 this.value = value; 662 } 663 664 /** 665 * Constructs a newly allocated {@code Integer} object that 666 * represents the {@code int} value indicated by the 667 * {@code String} parameter. The string is converted to an 668 * {@code int} value in exactly the manner used by the 669 * {@code parseInt} method for radix 10. 670 * 671 * @param s the {@code String} to be converted to an 672 * {@code Integer}. 673 * @exception NumberFormatException if the {@code String} does not 674 * contain a parsable integer. 675 * @see java.lang.Integer#parseInt(java.lang.String, int) 676 */ 677 public Integer(String s) throws NumberFormatException { 678 this.value = parseInt(s, 10); 679 } 680 681 /** 682 * Returns the value of this {@code Integer} as a {@code byte} 683 * after a narrowing primitive conversion. 684 * @jls 5.1.3 Narrowing Primitive Conversions 685 */ 686 public byte byteValue() { 687 return (byte)value; 688 } 689 690 /** 691 * Returns the value of this {@code Integer} as a {@code short} 692 * after a narrowing primitive conversion. 693 * @jls 5.1.3 Narrowing Primitive Conversions 694 */ 695 public short shortValue() { 696 return (short)value; 697 } 698 699 /** 700 * Returns the value of this {@code Integer} as an 701 * {@code int}. 702 */ 703 public int intValue() { 704 return value; 705 } 706 707 /** 708 * Returns the value of this {@code Integer} as a {@code long} 709 * after a widening primitive conversion. 710 * @jls 5.1.2 Widening Primitive Conversions 711 */ 712 public long longValue() { 713 return (long)value; 714 } 715 716 /** 717 * Returns the value of this {@code Integer} as a {@code float} 718 * after a widening primitive conversion. 719 * @jls 5.1.2 Widening Primitive Conversions 720 */ 721 public float floatValue() { 722 return (float)value; 723 } 724 725 /** 726 * Returns the value of this {@code Integer} as a {@code double} 727 * after a widening primitive conversion. 728 * @jls 5.1.2 Widening Primitive Conversions 729 */ 730 public double doubleValue() { 731 return (double)value; 732 } 733 734 /** 735 * Returns a {@code String} object representing this 736 * {@code Integer}'s value. The value is converted to signed 737 * decimal representation and returned as a string, exactly as if 738 * the integer value were given as an argument to the {@link 739 * java.lang.Integer#toString(int)} method. 740 * 741 * @return a string representation of the value of this object in 742 * base 10. 743 */ 744 public String toString() { 745 return toString(value); 746 } 747 748 /** 749 * Returns a hash code for this {@code Integer}. 750 * 751 * @return a hash code value for this object, equal to the 752 * primitive {@code int} value represented by this 753 * {@code Integer} object. 754 */ 755 public int hashCode() { 756 return value; 757 } 758 759 /** 760 * Compares this object to the specified object. The result is 761 * {@code true} if and only if the argument is not 762 * {@code null} and is an {@code Integer} object that 763 * contains the same {@code int} value as this object. 764 * 765 * @param obj the object to compare with. 766 * @return {@code true} if the objects are the same; 767 * {@code false} otherwise. 768 */ 769 public boolean equals(Object obj) { 770 if (obj instanceof Integer) { 771 return value == ((Integer)obj).intValue(); 772 } 773 return false; 774 } 775 776 /** 777 * Determines the integer value of the system property with the 778 * specified name. 779 * 780 * <p>The first argument is treated as the name of a system 781 * property. System properties are accessible through the {@link 782 * java.lang.System#getProperty(java.lang.String)} method. The 783 * string value of this property is then interpreted as an integer 784 * value using the grammar supported by {@link Integer#decode decode} and 785 * an {@code Integer} object representing this value is returned. 786 * 787 * <p>If there is no property with the specified name, if the 788 * specified name is empty or {@code null}, or if the property 789 * does not have the correct numeric format, then {@code null} is 790 * returned. 791 * 792 * <p>In other words, this method returns an {@code Integer} 793 * object equal to the value of: 794 * 795 * <blockquote> 796 * {@code getInteger(nm, null)} 797 * </blockquote> 798 * 799 * @param nm property name. 800 * @return the {@code Integer} value of the property. 801 * @throws SecurityException for the same reasons as 802 * {@link System#getProperty(String) System.getProperty} 803 * @see java.lang.System#getProperty(java.lang.String) 804 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 805 */ 806 public static Integer getInteger(String nm) { 807 return getInteger(nm, null); 808 } 809 810 /** 811 * Determines the integer value of the system property with the 812 * specified name. 813 * 814 * <p>The first argument is treated as the name of a system 815 * property. System properties are accessible through the {@link 816 * java.lang.System#getProperty(java.lang.String)} method. The 817 * string value of this property is then interpreted as an integer 818 * value using the grammar supported by {@link Integer#decode decode} and 819 * an {@code Integer} object representing this value is returned. 820 * 821 * <p>The second argument is the default value. An {@code Integer} object 822 * that represents the value of the second argument is returned if there 823 * is no property of the specified name, if the property does not have 824 * the correct numeric format, or if the specified name is empty or 825 * {@code null}. 826 * 827 * <p>In other words, this method returns an {@code Integer} object 828 * equal to the value of: 829 * 830 * <blockquote> 831 * {@code getInteger(nm, new Integer(val))} 832 * </blockquote> 833 * 834 * but in practice it may be implemented in a manner such as: 835 * 836 * <blockquote><pre> 837 * Integer result = getInteger(nm, null); 838 * return (result == null) ? new Integer(val) : result; 839 * </pre></blockquote> 840 * 841 * to avoid the unnecessary allocation of an {@code Integer} 842 * object when the default value is not needed. 843 * 844 * @param nm property name. 845 * @param val default value. 846 * @return the {@code Integer} value of the property. 847 * @throws SecurityException for the same reasons as 848 * {@link System#getProperty(String) System.getProperty} 849 * @see java.lang.System#getProperty(java.lang.String) 850 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 851 */ 852 public static Integer getInteger(String nm, int val) { 853 Integer result = getInteger(nm, null); 854 return (result == null) ? Integer.valueOf(val) : result; 855 } 856 857 /** 858 * Returns the integer value of the system property with the 859 * specified name. The first argument is treated as the name of a 860 * system property. System properties are accessible through the 861 * {@link java.lang.System#getProperty(java.lang.String)} method. 862 * The string value of this property is then interpreted as an 863 * integer value, as per the {@link Integer#decode decode} method, 864 * and an {@code Integer} object representing this value is 865 * returned; in summary: 866 * 867 * <ul><li>If the property value begins with the two ASCII characters 868 * {@code 0x} or the ASCII character {@code #}, not 869 * followed by a minus sign, then the rest of it is parsed as a 870 * hexadecimal integer exactly as by the method 871 * {@link #valueOf(java.lang.String, int)} with radix 16. 872 * <li>If the property value begins with the ASCII character 873 * {@code 0} followed by another character, it is parsed as an 874 * octal integer exactly as by the method 875 * {@link #valueOf(java.lang.String, int)} with radix 8. 876 * <li>Otherwise, the property value is parsed as a decimal integer 877 * exactly as by the method {@link #valueOf(java.lang.String, int)} 878 * with radix 10. 879 * </ul> 880 * 881 * <p>The second argument is the default value. The default value is 882 * returned if there is no property of the specified name, if the 883 * property does not have the correct numeric format, or if the 884 * specified name is empty or {@code null}. 885 * 886 * @param nm property name. 887 * @param val default value. 888 * @return the {@code Integer} value of the property. 889 * @throws SecurityException for the same reasons as 890 * {@link System#getProperty(String) System.getProperty} 891 * @see System#getProperty(java.lang.String) 892 * @see System#getProperty(java.lang.String, java.lang.String) 893 */ 894 public static Integer getInteger(String nm, Integer val) { 895 String v = null; 896 try { 897 v = System.getProperty(nm); 898 } catch (IllegalArgumentException | NullPointerException e) { 899 } 900 if (v != null) { 901 try { 902 return Integer.decode(v); 903 } catch (NumberFormatException e) { 904 } 905 } 906 return val; 907 } 908 909 /** 910 * Decodes a {@code String} into an {@code Integer}. 911 * Accepts decimal, hexadecimal, and octal numbers given 912 * by the following grammar: 913 * 914 * <blockquote> 915 * <dl> 916 * <dt><i>DecodableString:</i> 917 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 918 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 919 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 920 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 921 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 922 * <p> 923 * <dt><i>Sign:</i> 924 * <dd>{@code -} 925 * <dd>{@code +} 926 * </dl> 927 * </blockquote> 928 * 929 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 930 * are as defined in section 3.10.1 of 931 * <cite>The Java™ Language Specification</cite>, 932 * except that underscores are not accepted between digits. 933 * 934 * <p>The sequence of characters following an optional 935 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 936 * "{@code #}", or leading zero) is parsed as by the {@code 937 * Integer.parseInt} method with the indicated radix (10, 16, or 938 * 8). This sequence of characters must represent a positive 939 * value or a {@link NumberFormatException} will be thrown. The 940 * result is negated if first character of the specified {@code 941 * String} is the minus sign. No whitespace characters are 942 * permitted in the {@code String}. 943 * 944 * @param nm the {@code String} to decode. 945 * @return an {@code Integer} object holding the {@code int} 946 * value represented by {@code nm} 947 * @exception NumberFormatException if the {@code String} does not 948 * contain a parsable integer. 949 * @see java.lang.Integer#parseInt(java.lang.String, int) 950 */ 951 public static Integer decode(String nm) throws NumberFormatException { 952 int radix = 10; 953 int index = 0; 954 boolean negative = false; 955 Integer result; 956 957 if (nm.length() == 0) 958 throw new NumberFormatException("Zero length string"); 959 char firstChar = nm.charAt(0); 960 // Handle sign, if present 961 if (firstChar == '-') { 962 negative = true; 963 index++; 964 } else if (firstChar == '+') 965 index++; 966 967 // Handle radix specifier, if present 968 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 969 index += 2; 970 radix = 16; 971 } 972 else if (nm.startsWith("#", index)) { 973 index ++; 974 radix = 16; 975 } 976 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 977 index ++; 978 radix = 8; 979 } 980 981 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 982 throw new NumberFormatException("Sign character in wrong position"); 983 984 try { 985 result = Integer.valueOf(nm.substring(index), radix); 986 result = negative ? Integer.valueOf(-result.intValue()) : result; 987 } catch (NumberFormatException e) { 988 // If number is Integer.MIN_VALUE, we'll end up here. The next line 989 // handles this case, and causes any genuine format error to be 990 // rethrown. 991 String constant = negative ? ("-" + nm.substring(index)) 992 : nm.substring(index); 993 result = Integer.valueOf(constant, radix); 994 } 995 return result; 996 } 997 998 /** 999 * Compares two {@code Integer} objects numerically. 1000 * 1001 * @param anotherInteger the {@code Integer} to be compared. 1002 * @return the value {@code 0} if this {@code Integer} is 1003 * equal to the argument {@code Integer}; a value less than 1004 * {@code 0} if this {@code Integer} is numerically less 1005 * than the argument {@code Integer}; and a value greater 1006 * than {@code 0} if this {@code Integer} is numerically 1007 * greater than the argument {@code Integer} (signed 1008 * comparison). 1009 * @since 1.2 1010 */ 1011 public int compareTo(Integer anotherInteger) { 1012 return compare(this.value, anotherInteger.value); 1013 } 1014 1015 /** 1016 * Compares two {@code int} values numerically. 1017 * The value returned is identical to what would be returned by: 1018 * <pre> 1019 * Integer.valueOf(x).compareTo(Integer.valueOf(y)) 1020 * </pre> 1021 * 1022 * @param x the first {@code int} to compare 1023 * @param y the second {@code int} to compare 1024 * @return the value {@code 0} if {@code x == y}; 1025 * a value less than {@code 0} if {@code x < y}; and 1026 * a value greater than {@code 0} if {@code x > y} 1027 * @since 1.7 1028 */ 1029 public static int compare(int x, int y) { 1030 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1031 } 1032 1033 1034 // Bit twiddling 1035 1036 /** 1037 * The number of bits used to represent an {@code int} value in two's 1038 * complement binary form. 1039 * 1040 * @since 1.5 1041 */ 1042 public static final int SIZE = 32; 1043 1044 /** 1045 * Returns an {@code int} value with at most a single one-bit, in the 1046 * position of the highest-order ("leftmost") one-bit in the specified 1047 * {@code int} value. Returns zero if the specified value has no 1048 * one-bits in its two's complement binary representation, that is, if it 1049 * is equal to zero. 1050 * 1051 * @return an {@code int} value with a single one-bit, in the position 1052 * of the highest-order one-bit in the specified value, or zero if 1053 * the specified value is itself equal to zero. 1054 * @since 1.5 1055 */ 1056 public static int highestOneBit(int i) { 1057 // HD, Figure 3-1 1058 i |= (i >> 1); 1059 i |= (i >> 2); 1060 i |= (i >> 4); 1061 i |= (i >> 8); 1062 i |= (i >> 16); 1063 return i - (i >>> 1); 1064 } 1065 1066 /** 1067 * Returns an {@code int} value with at most a single one-bit, in the 1068 * position of the lowest-order ("rightmost") one-bit in the specified 1069 * {@code int} value. Returns zero if the specified value has no 1070 * one-bits in its two's complement binary representation, that is, if it 1071 * is equal to zero. 1072 * 1073 * @return an {@code int} value with a single one-bit, in the position 1074 * of the lowest-order one-bit in the specified value, or zero if 1075 * the specified value is itself equal to zero. 1076 * @since 1.5 1077 */ 1078 public static int lowestOneBit(int i) { 1079 // HD, Section 2-1 1080 return i & -i; 1081 } 1082 1083 /** 1084 * Returns the number of zero bits preceding the highest-order 1085 * ("leftmost") one-bit in the two's complement binary representation 1086 * of the specified {@code int} value. Returns 32 if the 1087 * specified value has no one-bits in its two's complement representation, 1088 * in other words if it is equal to zero. 1089 * 1090 * <p>Note that this method is closely related to the logarithm base 2. 1091 * For all positive {@code int} values x: 1092 * <ul> 1093 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 1094 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 1095 * </ul> 1096 * 1097 * @return the number of zero bits preceding the highest-order 1098 * ("leftmost") one-bit in the two's complement binary representation 1099 * of the specified {@code int} value, or 32 if the value 1100 * is equal to zero. 1101 * @since 1.5 1102 */ 1103 public static int numberOfLeadingZeros(int i) { 1104 // HD, Figure 5-6 1105 if (i == 0) 1106 return 32; 1107 int n = 1; 1108 if (i >>> 16 == 0) { n += 16; i <<= 16; } 1109 if (i >>> 24 == 0) { n += 8; i <<= 8; } 1110 if (i >>> 28 == 0) { n += 4; i <<= 4; } 1111 if (i >>> 30 == 0) { n += 2; i <<= 2; } 1112 n -= i >>> 31; 1113 return n; 1114 } 1115 1116 /** 1117 * Returns the number of zero bits following the lowest-order ("rightmost") 1118 * one-bit in the two's complement binary representation of the specified 1119 * {@code int} value. Returns 32 if the specified value has no 1120 * one-bits in its two's complement representation, in other words if it is 1121 * equal to zero. 1122 * 1123 * @return the number of zero bits following the lowest-order ("rightmost") 1124 * one-bit in the two's complement binary representation of the 1125 * specified {@code int} value, or 32 if the value is equal 1126 * to zero. 1127 * @since 1.5 1128 */ 1129 public static int numberOfTrailingZeros(int i) { 1130 // HD, Figure 5-14 1131 int y; 1132 if (i == 0) return 32; 1133 int n = 31; 1134 y = i <<16; if (y != 0) { n = n -16; i = y; } 1135 y = i << 8; if (y != 0) { n = n - 8; i = y; } 1136 y = i << 4; if (y != 0) { n = n - 4; i = y; } 1137 y = i << 2; if (y != 0) { n = n - 2; i = y; } 1138 return n - ((i << 1) >>> 31); 1139 } 1140 1141 /** 1142 * Returns the number of one-bits in the two's complement binary 1143 * representation of the specified {@code int} value. This function is 1144 * sometimes referred to as the <i>population count</i>. 1145 * 1146 * @return the number of one-bits in the two's complement binary 1147 * representation of the specified {@code int} value. 1148 * @since 1.5 1149 */ 1150 public static int bitCount(int i) { 1151 // HD, Figure 5-2 1152 i = i - ((i >>> 1) & 0x55555555); 1153 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); 1154 i = (i + (i >>> 4)) & 0x0f0f0f0f; 1155 i = i + (i >>> 8); 1156 i = i + (i >>> 16); 1157 return i & 0x3f; 1158 } 1159 1160 /** 1161 * Returns the value obtained by rotating the two's complement binary 1162 * representation of the specified {@code int} value left by the 1163 * specified number of bits. (Bits shifted out of the left hand, or 1164 * high-order, side reenter on the right, or low-order.) 1165 * 1166 * <p>Note that left rotation with a negative distance is equivalent to 1167 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1168 * distance)}. Note also that rotation by any multiple of 32 is a 1169 * no-op, so all but the last five bits of the rotation distance can be 1170 * ignored, even if the distance is negative: {@code rotateLeft(val, 1171 * distance) == rotateLeft(val, distance & 0x1F)}. 1172 * 1173 * @return the value obtained by rotating the two's complement binary 1174 * representation of the specified {@code int} value left by the 1175 * specified number of bits. 1176 * @since 1.5 1177 */ 1178 public static int rotateLeft(int i, int distance) { 1179 return (i << distance) | (i >>> -distance); 1180 } 1181 1182 /** 1183 * Returns the value obtained by rotating the two's complement binary 1184 * representation of the specified {@code int} value right by the 1185 * specified number of bits. (Bits shifted out of the right hand, or 1186 * low-order, side reenter on the left, or high-order.) 1187 * 1188 * <p>Note that right rotation with a negative distance is equivalent to 1189 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1190 * distance)}. Note also that rotation by any multiple of 32 is a 1191 * no-op, so all but the last five bits of the rotation distance can be 1192 * ignored, even if the distance is negative: {@code rotateRight(val, 1193 * distance) == rotateRight(val, distance & 0x1F)}. 1194 * 1195 * @return the value obtained by rotating the two's complement binary 1196 * representation of the specified {@code int} value right by the 1197 * specified number of bits. 1198 * @since 1.5 1199 */ 1200 public static int rotateRight(int i, int distance) { 1201 return (i >>> distance) | (i << -distance); 1202 } 1203 1204 /** 1205 * Returns the value obtained by reversing the order of the bits in the 1206 * two's complement binary representation of the specified {@code int} 1207 * value. 1208 * 1209 * @return the value obtained by reversing order of the bits in the 1210 * specified {@code int} value. 1211 * @since 1.5 1212 */ 1213 public static int reverse(int i) { 1214 // HD, Figure 7-1 1215 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; 1216 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; 1217 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; 1218 i = (i << 24) | ((i & 0xff00) << 8) | 1219 ((i >>> 8) & 0xff00) | (i >>> 24); 1220 return i; 1221 } 1222 1223 /** 1224 * Returns the signum function of the specified {@code int} value. (The 1225 * return value is -1 if the specified value is negative; 0 if the 1226 * specified value is zero; and 1 if the specified value is positive.) 1227 * 1228 * @return the signum function of the specified {@code int} value. 1229 * @since 1.5 1230 */ 1231 public static int signum(int i) { 1232 // HD, Section 2-7 1233 return (i >> 31) | (-i >>> 31); 1234 } 1235 1236 /** 1237 * Returns the value obtained by reversing the order of the bytes in the 1238 * two's complement representation of the specified {@code int} value. 1239 * 1240 * @return the value obtained by reversing the bytes in the specified 1241 * {@code int} value. 1242 * @since 1.5 1243 */ 1244 public static int reverseBytes(int i) { 1245 return ((i >>> 24) ) | 1246 ((i >> 8) & 0xFF00) | 1247 ((i << 8) & 0xFF0000) | 1248 ((i << 24)); 1249 } 1250 1251 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1252 private static final long serialVersionUID = 1360826667806852920L; 1253 }