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