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