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 the end of the sequence. 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 radix the radix to be used while parsing {@code s}. 606 * @param beginIndex the beginning index, inclusive. 607 * @return the signed {@code int} represented by the subsequence in 608 * the specified radix. 609 * @throws NullPointerException if {@code s} is null. 610 * @throws IndexOutOfBoundsException if {@code beginIndex} is 611 * negative, or if {@code beginIndex} is greater than 612 * {@code s.length()}. 613 * @throws NumberFormatException if the {@code CharSequence} does not 614 * contain a parsable {@code int} in the specified 615 * {@code radix}, or if {@code radix} is either smaller than 616 * {@link java.lang.Character#MIN_RADIX} or larger than 617 * {@link java.lang.Character#MAX_RADIX}. 618 * @since 1.9 619 */ 620 public static int parseInt(CharSequence s, int radix, int beginIndex) 621 throws NumberFormatException { 622 // forces an implicit null check of s 623 return parseInt(s, radix, beginIndex, s.length()); 624 } 625 626 /** 627 * Parses the {@link CharSequence} argument as a signed {@code int} in the 628 * specified {@code radix}, beginning at the specified {@code beginIndex} 629 * and extending to {@code endIndex - 1}. 630 * 631 * <p>The method does not take steps to guard against the 632 * {@code CharSequence} being mutated while parsing. 633 * 634 * @param s the {@code CharSequence} containing the {@code int} 635 * representation to be parsed 636 * @param radix the radix to be used while parsing {@code s}. 637 * @param beginIndex the beginning index, inclusive. 638 * @param endIndex the ending index, exclusive. 639 * @return the signed {@code int} represented by the subsequence in 640 * the specified radix. 641 * @throws NullPointerException if {@code s} is null. 642 * @throws IndexOutOfBoundsException if {@code beginIndex} is 643 * negative, or if {@code beginIndex} is greater than 644 * {@code endIndex} or if {@code endIndex} is greater than 645 * {@code s.length()}. 646 * @throws NumberFormatException if the {@code CharSequence} does not 647 * contain a parsable {@code int} in the specified 648 * {@code radix}, or if {@code radix} is either smaller than 649 * {@link java.lang.Character#MIN_RADIX} or larger than 650 * {@link java.lang.Character#MAX_RADIX}. 651 * @since 1.9 652 */ 653 public static int parseInt(CharSequence s, int radix, int beginIndex, int endIndex) 654 throws NumberFormatException { 655 s = Objects.requireNonNull(s); 656 657 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 658 throw new IndexOutOfBoundsException(); 659 } 660 if (radix < Character.MIN_RADIX) { 661 throw new NumberFormatException("radix " + radix + 662 " less than Character.MIN_RADIX"); 663 } 664 if (radix > Character.MAX_RADIX) { 665 throw new NumberFormatException("radix " + radix + 666 " greater than Character.MAX_RADIX"); 667 } 668 669 boolean negative = false; 670 int i = beginIndex; 671 int limit = -Integer.MAX_VALUE; 672 673 if (i < endIndex) { 674 char firstChar = s.charAt(i); 675 if (firstChar < '0') { // Possible leading "+" or "-" 676 if (firstChar == '-') { 677 negative = true; 678 limit = Integer.MIN_VALUE; 679 } else if (firstChar != '+') { 680 throw NumberFormatException.forCharSequence(s, beginIndex, 681 endIndex, i); 682 } 683 i++; 684 if (i == endIndex) { // Cannot have lone "+" or "-" 685 throw NumberFormatException.forCharSequence(s, beginIndex, 686 endIndex, i); 687 } 688 } 689 int multmin = limit / radix; 690 int result = 0; 691 while (i < endIndex) { 692 // Accumulating negatively avoids surprises near MAX_VALUE 693 int digit = Character.digit(s.charAt(i++), radix); 694 if (digit < 0 || result < multmin) { 695 throw NumberFormatException.forCharSequence(s, beginIndex, 696 endIndex, i); 697 } 698 result *= radix; 699 if (result < limit + digit) { 700 throw NumberFormatException.forCharSequence(s, beginIndex, 701 endIndex, i); 702 } 703 result -= digit; 704 } 705 return negative ? result : -result; 706 } else { 707 throw NumberFormatException.forInputString(""); 708 } 709 } 710 711 /** 712 * Parses the string argument as a signed decimal integer. The 713 * characters in the string must all be decimal digits, except 714 * that the first character may be an ASCII minus sign {@code '-'} 715 * ({@code '\u005Cu002D'}) to indicate a negative value or an 716 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 717 * indicate a positive value. The resulting integer value is 718 * returned, exactly as if the argument and the radix 10 were 719 * given as arguments to the {@link #parseInt(java.lang.String, 720 * int)} method. 721 * 722 * @param s a {@code String} containing the {@code int} 723 * representation to be parsed 724 * @return the integer value represented by the argument in decimal. 725 * @exception NumberFormatException if the string does not contain a 726 * parsable integer. 727 */ 728 public static int parseInt(String s) throws NumberFormatException { 729 return parseInt(s,10); 730 } 731 732 /** 733 * Parses the string argument as an unsigned integer in the radix 734 * specified by the second argument. An unsigned integer maps the 735 * values usually associated with negative numbers to positive 736 * numbers larger than {@code MAX_VALUE}. 737 * 738 * The characters in the string must all be digits of the 739 * specified radix (as determined by whether {@link 740 * java.lang.Character#digit(char, int)} returns a nonnegative 741 * value), except that the first character may be an ASCII plus 742 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 743 * integer value is returned. 744 * 745 * <p>An exception of type {@code NumberFormatException} is 746 * thrown if any of the following situations occurs: 747 * <ul> 748 * <li>The first argument is {@code null} or is a string of 749 * length zero. 750 * 751 * <li>The radix is either smaller than 752 * {@link java.lang.Character#MIN_RADIX} or 753 * larger than {@link java.lang.Character#MAX_RADIX}. 754 * 755 * <li>Any character of the string is not a digit of the specified 756 * radix, except that the first character may be a plus sign 757 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 758 * string is longer than length 1. 759 * 760 * <li>The value represented by the string is larger than the 761 * largest unsigned {@code int}, 2<sup>32</sup>-1. 762 * 763 * </ul> 764 * 765 * 766 * @param s the {@code String} containing the unsigned integer 767 * representation to be parsed 768 * @param radix the radix to be used while parsing {@code s}. 769 * @return the integer represented by the string argument in the 770 * specified radix. 771 * @throws NumberFormatException if the {@code String} 772 * does not contain a parsable {@code int}. 773 * @since 1.8 774 */ 775 public static int parseUnsignedInt(String s, int radix) 776 throws NumberFormatException { 777 if (s == null) { 778 throw new NumberFormatException("null"); 779 } 780 781 int len = s.length(); 782 if (len > 0) { 783 char firstChar = s.charAt(0); 784 if (firstChar == '-') { 785 throw new 786 NumberFormatException(String.format("Illegal leading minus sign " + 787 "on unsigned string %s.", s)); 788 } else { 789 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits 790 (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits 791 return parseInt(s, radix); 792 } else { 793 long ell = Long.parseLong(s, radix); 794 if ((ell & 0xffff_ffff_0000_0000L) == 0) { 795 return (int) ell; 796 } else { 797 throw new 798 NumberFormatException(String.format("String value %s exceeds " + 799 "range of unsigned int.", s)); 800 } 801 } 802 } 803 } else { 804 throw NumberFormatException.forInputString(s); 805 } 806 } 807 808 /** 809 * Parses the {@link CharSequence} argument as an unsigned {@code int} in 810 * the specified {@code radix}, beginning at the specified 811 * {@code beginIndex} and extending to the end of the sequence. 812 * 813 * <p>The method does not take steps to guard against the 814 * {@code CharSequence} being mutated while parsing. 815 * 816 * @param s the {@code CharSequence} containing the unsigned 817 * {@code int} representation to be parsed 818 * @param radix the radix to be used while parsing {@code s}. 819 * @param beginIndex the beginning index, inclusive. 820 * @return the unsigned {@code int} represented by the subsequence in 821 * the specified radix. 822 * @throws NullPointerException if {@code s} is null. 823 * @throws IndexOutOfBoundsException if {@code beginIndex} is 824 * negative, or if {@code beginIndex} is greater than 825 * {@code s.length()}. 826 * @throws NumberFormatException if the {@code CharSequence} does not 827 * contain a parsable unsigned {@code int} in the specified 828 * {@code radix}, or if {@code radix} is either smaller than 829 * {@link java.lang.Character#MIN_RADIX} or larger than 830 * {@link java.lang.Character#MAX_RADIX}. 831 * @since 1.9 832 */ 833 public static int parseUnsignedInt(CharSequence s, int radix, int beginIndex) 834 throws NumberFormatException { 835 // forces an implicit null check of s 836 return parseUnsignedInt(s, radix, beginIndex, s.length()); 837 } 838 839 /** 840 * Parses the {@link CharSequence} argument as an unsigned {@code int} in 841 * the specified {@code radix}, beginning at the specified 842 * {@code beginIndex} and extending to {@code endIndex - 1}. 843 * 844 * <p>The method does not take steps to guard against the 845 * {@code CharSequence} being mutated while parsing. 846 * 847 * @param s the {@code CharSequence} containing the unsigned 848 * {@code int} representation to be parsed 849 * @param radix the radix to be used while parsing {@code s}. 850 * @param beginIndex the beginning index, inclusive. 851 * @param endIndex the ending index, exclusive. 852 * @return the unsigned {@code int} represented by the subsequence in 853 * the specified radix. 854 * @throws NullPointerException if {@code s} is null. 855 * @throws IndexOutOfBoundsException if {@code beginIndex} is 856 * negative, or if {@code beginIndex} is greater than 857 * {@code endIndex} or if {@code endIndex} is greater than 858 * {@code s.length()}. 859 * @throws NumberFormatException if the {@code CharSequence} does not 860 * contain a parsable unsigned {@code int} in the specified 861 * {@code radix}, or if {@code radix} is either smaller than 862 * {@link java.lang.Character#MIN_RADIX} or larger than 863 * {@link java.lang.Character#MAX_RADIX}. 864 * @since 1.9 865 */ 866 public static int parseUnsignedInt(CharSequence s, int radix, int beginIndex, int endIndex) 867 throws NumberFormatException { 868 s = Objects.requireNonNull(s); 869 870 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 871 throw new IndexOutOfBoundsException(); 872 } 873 int start = beginIndex, len = endIndex - beginIndex; 874 875 if (len > 0) { 876 char firstChar = s.charAt(start); 877 if (firstChar == '-') { 878 throw new 879 NumberFormatException(String.format("Illegal leading minus sign " + 880 "on unsigned string %s.", s)); 881 } else { 882 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits 883 (radix == 10 && len <= 9)) { // Integer.MAX_VALUE in base 10 is 10 digits 884 return parseInt(s, radix, start, start + len); 885 } else { 886 long ell = Long.parseLong(s, radix, start, start + len); 887 if ((ell & 0xffff_ffff_0000_0000L) == 0) { 888 return (int) ell; 889 } else { 890 throw new 891 NumberFormatException(String.format("String value %s exceeds " + 892 "range of unsigned int.", s)); 893 } 894 } 895 } 896 } else { 897 throw new NumberFormatException(""); 898 } 899 } 900 901 /** 902 * Parses the string argument as an unsigned decimal integer. The 903 * characters in the string must all be decimal digits, except 904 * that the first character may be an an ASCII plus sign {@code 905 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 906 * is returned, exactly as if the argument and the radix 10 were 907 * given as arguments to the {@link 908 * #parseUnsignedInt(java.lang.String, int)} method. 909 * 910 * @param s a {@code String} containing the unsigned {@code int} 911 * representation to be parsed 912 * @return the unsigned integer value represented by the argument in decimal. 913 * @throws NumberFormatException if the string does not contain a 914 * parsable unsigned integer. 915 * @since 1.8 916 */ 917 public static int parseUnsignedInt(String s) throws NumberFormatException { 918 return parseUnsignedInt(s, 10); 919 } 920 921 /** 922 * Returns an {@code Integer} object holding the value 923 * extracted from the specified {@code String} when parsed 924 * with the radix given by the second argument. The first argument 925 * is interpreted as representing a signed integer in the radix 926 * specified by the second argument, exactly as if the arguments 927 * were given to the {@link #parseInt(java.lang.String, int)} 928 * method. The result is an {@code Integer} object that 929 * represents the integer value specified by the string. 930 * 931 * <p>In other words, this method returns an {@code Integer} 932 * object equal to the value of: 933 * 934 * <blockquote> 935 * {@code new Integer(Integer.parseInt(s, radix))} 936 * </blockquote> 937 * 938 * @param s the string to be parsed. 939 * @param radix the radix to be used in interpreting {@code s} 940 * @return an {@code Integer} object holding the value 941 * represented by the string argument in the specified 942 * radix. 943 * @exception NumberFormatException if the {@code String} 944 * does not contain a parsable {@code int}. 945 */ 946 public static Integer valueOf(String s, int radix) throws NumberFormatException { 947 return Integer.valueOf(parseInt(s,radix)); 948 } 949 950 /** 951 * Returns an {@code Integer} object holding the 952 * value of the specified {@code String}. The argument is 953 * interpreted as representing a signed decimal integer, exactly 954 * as if the argument were given to the {@link 955 * #parseInt(java.lang.String)} method. The result is an 956 * {@code Integer} object that represents the integer value 957 * specified by the string. 958 * 959 * <p>In other words, this method returns an {@code Integer} 960 * object equal to the value of: 961 * 962 * <blockquote> 963 * {@code new Integer(Integer.parseInt(s))} 964 * </blockquote> 965 * 966 * @param s the string to be parsed. 967 * @return an {@code Integer} object holding the value 968 * represented by the string argument. 969 * @exception NumberFormatException if the string cannot be parsed 970 * as an integer. 971 */ 972 public static Integer valueOf(String s) throws NumberFormatException { 973 return Integer.valueOf(parseInt(s, 10)); 974 } 975 976 /** 977 * Cache to support the object identity semantics of autoboxing for values between 978 * -128 and 127 (inclusive) as required by JLS. 979 * 980 * The cache is initialized on first usage. The size of the cache 981 * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. 982 * During VM initialization, java.lang.Integer.IntegerCache.high property 983 * may be set and saved in the private system properties in the 984 * sun.misc.VM class. 985 */ 986 987 private static class IntegerCache { 988 static final int low = -128; 989 static final int high; 990 static final Integer cache[]; 991 992 static { 993 // high value may be configured by property 994 int h = 127; 995 String integerCacheHighPropValue = 996 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 997 if (integerCacheHighPropValue != null) { 998 try { 999 int i = parseInt(integerCacheHighPropValue); 1000 i = Math.max(i, 127); 1001 // Maximum array size is Integer.MAX_VALUE 1002 h = Math.min(i, Integer.MAX_VALUE - (-low) -1); 1003 } catch( NumberFormatException nfe) { 1004 // If the property cannot be parsed into an int, ignore it. 1005 } 1006 } 1007 high = h; 1008 1009 cache = new Integer[(high - low) + 1]; 1010 int j = low; 1011 for(int k = 0; k < cache.length; k++) 1012 cache[k] = new Integer(j++); 1013 1014 // range [-128, 127] must be interned (JLS7 5.1.7) 1015 assert IntegerCache.high >= 127; 1016 } 1017 1018 private IntegerCache() {} 1019 } 1020 1021 /** 1022 * Returns an {@code Integer} instance representing the specified 1023 * {@code int} value. If a new {@code Integer} instance is not 1024 * required, this method should generally be used in preference to 1025 * the constructor {@link #Integer(int)}, as this method is likely 1026 * to yield significantly better space and time performance by 1027 * caching frequently requested values. 1028 * 1029 * This method will always cache values in the range -128 to 127, 1030 * inclusive, and may cache other values outside of this range. 1031 * 1032 * @param i an {@code int} value. 1033 * @return an {@code Integer} instance representing {@code i}. 1034 * @since 1.5 1035 */ 1036 public static Integer valueOf(int i) { 1037 if (i >= IntegerCache.low && i <= IntegerCache.high) 1038 return IntegerCache.cache[i + (-IntegerCache.low)]; 1039 return new Integer(i); 1040 } 1041 1042 /** 1043 * The value of the {@code Integer}. 1044 * 1045 * @serial 1046 */ 1047 private final int value; 1048 1049 /** 1050 * Constructs a newly allocated {@code Integer} object that 1051 * represents the specified {@code int} value. 1052 * 1053 * @param value the value to be represented by the 1054 * {@code Integer} object. 1055 */ 1056 public Integer(int value) { 1057 this.value = value; 1058 } 1059 1060 /** 1061 * Constructs a newly allocated {@code Integer} object that 1062 * represents the {@code int} value indicated by the 1063 * {@code String} parameter. The string is converted to an 1064 * {@code int} value in exactly the manner used by the 1065 * {@code parseInt} method for radix 10. 1066 * 1067 * @param s the {@code String} to be converted to an 1068 * {@code Integer}. 1069 * @exception NumberFormatException if the {@code String} does not 1070 * contain a parsable integer. 1071 * @see java.lang.Integer#parseInt(java.lang.String, int) 1072 */ 1073 public Integer(String s) throws NumberFormatException { 1074 this.value = parseInt(s, 10); 1075 } 1076 1077 /** 1078 * Returns the value of this {@code Integer} as a {@code byte} 1079 * after a narrowing primitive conversion. 1080 * @jls 5.1.3 Narrowing Primitive Conversions 1081 */ 1082 public byte byteValue() { 1083 return (byte)value; 1084 } 1085 1086 /** 1087 * Returns the value of this {@code Integer} as a {@code short} 1088 * after a narrowing primitive conversion. 1089 * @jls 5.1.3 Narrowing Primitive Conversions 1090 */ 1091 public short shortValue() { 1092 return (short)value; 1093 } 1094 1095 /** 1096 * Returns the value of this {@code Integer} as an 1097 * {@code int}. 1098 */ 1099 public int intValue() { 1100 return value; 1101 } 1102 1103 /** 1104 * Returns the value of this {@code Integer} as a {@code long} 1105 * after a widening primitive conversion. 1106 * @jls 5.1.2 Widening Primitive Conversions 1107 * @see Integer#toUnsignedLong(int) 1108 */ 1109 public long longValue() { 1110 return (long)value; 1111 } 1112 1113 /** 1114 * Returns the value of this {@code Integer} as a {@code float} 1115 * after a widening primitive conversion. 1116 * @jls 5.1.2 Widening Primitive Conversions 1117 */ 1118 public float floatValue() { 1119 return (float)value; 1120 } 1121 1122 /** 1123 * Returns the value of this {@code Integer} as a {@code double} 1124 * after a widening primitive conversion. 1125 * @jls 5.1.2 Widening Primitive Conversions 1126 */ 1127 public double doubleValue() { 1128 return (double)value; 1129 } 1130 1131 /** 1132 * Returns a {@code String} object representing this 1133 * {@code Integer}'s value. The value is converted to signed 1134 * decimal representation and returned as a string, exactly as if 1135 * the integer value were given as an argument to the {@link 1136 * java.lang.Integer#toString(int)} method. 1137 * 1138 * @return a string representation of the value of this object in 1139 * base 10. 1140 */ 1141 public String toString() { 1142 return toString(value); 1143 } 1144 1145 /** 1146 * Returns a hash code for this {@code Integer}. 1147 * 1148 * @return a hash code value for this object, equal to the 1149 * primitive {@code int} value represented by this 1150 * {@code Integer} object. 1151 */ 1152 @Override 1153 public int hashCode() { 1154 return Integer.hashCode(value); 1155 } 1156 1157 /** 1158 * Returns a hash code for a {@code int} value; compatible with 1159 * {@code Integer.hashCode()}. 1160 * 1161 * @param value the value to hash 1162 * @since 1.8 1163 * 1164 * @return a hash code value for a {@code int} value. 1165 */ 1166 public static int hashCode(int value) { 1167 return value; 1168 } 1169 1170 /** 1171 * Compares this object to the specified object. The result is 1172 * {@code true} if and only if the argument is not 1173 * {@code null} and is an {@code Integer} object that 1174 * contains the same {@code int} value as this object. 1175 * 1176 * @param obj the object to compare with. 1177 * @return {@code true} if the objects are the same; 1178 * {@code false} otherwise. 1179 */ 1180 public boolean equals(Object obj) { 1181 if (obj instanceof Integer) { 1182 return value == ((Integer)obj).intValue(); 1183 } 1184 return false; 1185 } 1186 1187 /** 1188 * Determines the integer value of the system property with the 1189 * specified name. 1190 * 1191 * <p>The first argument is treated as the name of a system 1192 * property. System properties are accessible through the {@link 1193 * java.lang.System#getProperty(java.lang.String)} method. The 1194 * string value of this property is then interpreted as an integer 1195 * value using the grammar supported by {@link Integer#decode decode} and 1196 * an {@code Integer} object representing this value is returned. 1197 * 1198 * <p>If there is no property with the specified name, if the 1199 * specified name is empty or {@code null}, or if the property 1200 * does not have the correct numeric format, then {@code null} is 1201 * returned. 1202 * 1203 * <p>In other words, this method returns an {@code Integer} 1204 * object equal to the value of: 1205 * 1206 * <blockquote> 1207 * {@code getInteger(nm, null)} 1208 * </blockquote> 1209 * 1210 * @param nm property name. 1211 * @return the {@code Integer} value of the property. 1212 * @throws SecurityException for the same reasons as 1213 * {@link System#getProperty(String) System.getProperty} 1214 * @see java.lang.System#getProperty(java.lang.String) 1215 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1216 */ 1217 public static Integer getInteger(String nm) { 1218 return getInteger(nm, null); 1219 } 1220 1221 /** 1222 * Determines the integer value of the system property with the 1223 * specified name. 1224 * 1225 * <p>The first argument is treated as the name of a system 1226 * property. System properties are accessible through the {@link 1227 * java.lang.System#getProperty(java.lang.String)} method. The 1228 * string value of this property is then interpreted as an integer 1229 * value using the grammar supported by {@link Integer#decode decode} and 1230 * an {@code Integer} object representing this value is returned. 1231 * 1232 * <p>The second argument is the default value. An {@code Integer} object 1233 * that represents the value of the second argument is returned if there 1234 * is no property of the specified name, if the property does not have 1235 * the correct numeric format, or if the specified name is empty or 1236 * {@code null}. 1237 * 1238 * <p>In other words, this method returns an {@code Integer} object 1239 * equal to the value of: 1240 * 1241 * <blockquote> 1242 * {@code getInteger(nm, new Integer(val))} 1243 * </blockquote> 1244 * 1245 * but in practice it may be implemented in a manner such as: 1246 * 1247 * <blockquote><pre> 1248 * Integer result = getInteger(nm, null); 1249 * return (result == null) ? new Integer(val) : result; 1250 * </pre></blockquote> 1251 * 1252 * to avoid the unnecessary allocation of an {@code Integer} 1253 * object when the default value is not needed. 1254 * 1255 * @param nm property name. 1256 * @param val default value. 1257 * @return the {@code Integer} value of the property. 1258 * @throws SecurityException for the same reasons as 1259 * {@link System#getProperty(String) System.getProperty} 1260 * @see java.lang.System#getProperty(java.lang.String) 1261 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1262 */ 1263 public static Integer getInteger(String nm, int val) { 1264 Integer result = getInteger(nm, null); 1265 return (result == null) ? Integer.valueOf(val) : result; 1266 } 1267 1268 /** 1269 * Returns the integer value of the system property with the 1270 * specified name. The first argument is treated as the name of a 1271 * system property. System properties are accessible through the 1272 * {@link java.lang.System#getProperty(java.lang.String)} method. 1273 * The string value of this property is then interpreted as an 1274 * integer value, as per the {@link Integer#decode decode} method, 1275 * and an {@code Integer} object representing this value is 1276 * returned; in summary: 1277 * 1278 * <ul><li>If the property value begins with the two ASCII characters 1279 * {@code 0x} or the ASCII character {@code #}, not 1280 * followed by a minus sign, then the rest of it is parsed as a 1281 * hexadecimal integer exactly as by the method 1282 * {@link #valueOf(java.lang.String, int)} with radix 16. 1283 * <li>If the property value begins with the ASCII character 1284 * {@code 0} followed by another character, it is parsed as an 1285 * octal integer exactly as by the method 1286 * {@link #valueOf(java.lang.String, int)} with radix 8. 1287 * <li>Otherwise, the property value is parsed as a decimal integer 1288 * exactly as by the method {@link #valueOf(java.lang.String, int)} 1289 * with radix 10. 1290 * </ul> 1291 * 1292 * <p>The second argument is the default value. The default value is 1293 * returned if there is no property of the specified name, if the 1294 * property does not have the correct numeric format, or if the 1295 * specified name is empty or {@code null}. 1296 * 1297 * @param nm property name. 1298 * @param val default value. 1299 * @return the {@code Integer} value of the property. 1300 * @throws SecurityException for the same reasons as 1301 * {@link System#getProperty(String) System.getProperty} 1302 * @see System#getProperty(java.lang.String) 1303 * @see System#getProperty(java.lang.String, java.lang.String) 1304 */ 1305 public static Integer getInteger(String nm, Integer val) { 1306 String v = null; 1307 try { 1308 v = System.getProperty(nm); 1309 } catch (IllegalArgumentException | NullPointerException e) { 1310 } 1311 if (v != null) { 1312 try { 1313 return Integer.decode(v); 1314 } catch (NumberFormatException e) { 1315 } 1316 } 1317 return val; 1318 } 1319 1320 /** 1321 * Decodes a {@code String} into an {@code Integer}. 1322 * Accepts decimal, hexadecimal, and octal numbers given 1323 * by the following grammar: 1324 * 1325 * <blockquote> 1326 * <dl> 1327 * <dt><i>DecodableString:</i> 1328 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1329 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1330 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1331 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1332 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1333 * 1334 * <dt><i>Sign:</i> 1335 * <dd>{@code -} 1336 * <dd>{@code +} 1337 * </dl> 1338 * </blockquote> 1339 * 1340 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1341 * are as defined in section 3.10.1 of 1342 * <cite>The Java™ Language Specification</cite>, 1343 * except that underscores are not accepted between digits. 1344 * 1345 * <p>The sequence of characters following an optional 1346 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1347 * "{@code #}", or leading zero) is parsed as by the {@code 1348 * Integer.parseInt} method with the indicated radix (10, 16, or 1349 * 8). This sequence of characters must represent a positive 1350 * value or a {@link NumberFormatException} will be thrown. The 1351 * result is negated if first character of the specified {@code 1352 * String} is the minus sign. No whitespace characters are 1353 * permitted in the {@code String}. 1354 * 1355 * @param nm the {@code String} to decode. 1356 * @return an {@code Integer} object holding the {@code int} 1357 * value represented by {@code nm} 1358 * @exception NumberFormatException if the {@code String} does not 1359 * contain a parsable integer. 1360 * @see java.lang.Integer#parseInt(java.lang.String, int) 1361 */ 1362 public static Integer decode(String nm) throws NumberFormatException { 1363 int radix = 10; 1364 int index = 0; 1365 boolean negative = false; 1366 Integer result; 1367 1368 if (nm.length() == 0) 1369 throw new NumberFormatException("Zero length string"); 1370 char firstChar = nm.charAt(0); 1371 // Handle sign, if present 1372 if (firstChar == '-') { 1373 negative = true; 1374 index++; 1375 } else if (firstChar == '+') 1376 index++; 1377 1378 // Handle radix specifier, if present 1379 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1380 index += 2; 1381 radix = 16; 1382 } 1383 else if (nm.startsWith("#", index)) { 1384 index ++; 1385 radix = 16; 1386 } 1387 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1388 index ++; 1389 radix = 8; 1390 } 1391 1392 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1393 throw new NumberFormatException("Sign character in wrong position"); 1394 1395 try { 1396 result = Integer.valueOf(nm.substring(index), radix); 1397 result = negative ? Integer.valueOf(-result.intValue()) : result; 1398 } catch (NumberFormatException e) { 1399 // If number is Integer.MIN_VALUE, we'll end up here. The next line 1400 // handles this case, and causes any genuine format error to be 1401 // rethrown. 1402 String constant = negative ? ("-" + nm.substring(index)) 1403 : nm.substring(index); 1404 result = Integer.valueOf(constant, radix); 1405 } 1406 return result; 1407 } 1408 1409 /** 1410 * Compares two {@code Integer} objects numerically. 1411 * 1412 * @param anotherInteger the {@code Integer} to be compared. 1413 * @return the value {@code 0} if this {@code Integer} is 1414 * equal to the argument {@code Integer}; a value less than 1415 * {@code 0} if this {@code Integer} is numerically less 1416 * than the argument {@code Integer}; and a value greater 1417 * than {@code 0} if this {@code Integer} is numerically 1418 * greater than the argument {@code Integer} (signed 1419 * comparison). 1420 * @since 1.2 1421 */ 1422 public int compareTo(Integer anotherInteger) { 1423 return compare(this.value, anotherInteger.value); 1424 } 1425 1426 /** 1427 * Compares two {@code int} values numerically. 1428 * The value returned is identical to what would be returned by: 1429 * <pre> 1430 * Integer.valueOf(x).compareTo(Integer.valueOf(y)) 1431 * </pre> 1432 * 1433 * @param x the first {@code int} to compare 1434 * @param y the second {@code int} to compare 1435 * @return the value {@code 0} if {@code x == y}; 1436 * a value less than {@code 0} if {@code x < y}; and 1437 * a value greater than {@code 0} if {@code x > y} 1438 * @since 1.7 1439 */ 1440 public static int compare(int x, int y) { 1441 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1442 } 1443 1444 /** 1445 * Compares two {@code int} values numerically treating the values 1446 * as unsigned. 1447 * 1448 * @param x the first {@code int} to compare 1449 * @param y the second {@code int} to compare 1450 * @return the value {@code 0} if {@code x == y}; a value less 1451 * than {@code 0} if {@code x < y} as unsigned values; and 1452 * a value greater than {@code 0} if {@code x > y} as 1453 * unsigned values 1454 * @since 1.8 1455 */ 1456 public static int compareUnsigned(int x, int y) { 1457 return compare(x + MIN_VALUE, y + MIN_VALUE); 1458 } 1459 1460 /** 1461 * Converts the argument to a {@code long} by an unsigned 1462 * conversion. In an unsigned conversion to a {@code long}, the 1463 * high-order 32 bits of the {@code long} are zero and the 1464 * low-order 32 bits are equal to the bits of the integer 1465 * argument. 1466 * 1467 * Consequently, zero and positive {@code int} values are mapped 1468 * to a numerically equal {@code long} value and negative {@code 1469 * int} values are mapped to a {@code long} value equal to the 1470 * input plus 2<sup>32</sup>. 1471 * 1472 * @param x the value to convert to an unsigned {@code long} 1473 * @return the argument converted to {@code long} by an unsigned 1474 * conversion 1475 * @since 1.8 1476 */ 1477 public static long toUnsignedLong(int x) { 1478 return ((long) x) & 0xffffffffL; 1479 } 1480 1481 /** 1482 * Returns the unsigned quotient of dividing the first argument by 1483 * the second where each argument and the result is interpreted as 1484 * an unsigned value. 1485 * 1486 * <p>Note that in two's complement arithmetic, the three other 1487 * basic arithmetic operations of add, subtract, and multiply are 1488 * bit-wise identical if the two operands are regarded as both 1489 * being signed or both being unsigned. Therefore separate {@code 1490 * addUnsigned}, etc. methods are not provided. 1491 * 1492 * @param dividend the value to be divided 1493 * @param divisor the value doing the dividing 1494 * @return the unsigned quotient of the first argument divided by 1495 * the second argument 1496 * @see #remainderUnsigned 1497 * @since 1.8 1498 */ 1499 public static int divideUnsigned(int dividend, int divisor) { 1500 // In lieu of tricky code, for now just use long arithmetic. 1501 return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor)); 1502 } 1503 1504 /** 1505 * Returns the unsigned remainder from dividing the first argument 1506 * by the second where each argument and the result is interpreted 1507 * as an unsigned value. 1508 * 1509 * @param dividend the value to be divided 1510 * @param divisor the value doing the dividing 1511 * @return the unsigned remainder of the first argument divided by 1512 * the second argument 1513 * @see #divideUnsigned 1514 * @since 1.8 1515 */ 1516 public static int remainderUnsigned(int dividend, int divisor) { 1517 // In lieu of tricky code, for now just use long arithmetic. 1518 return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor)); 1519 } 1520 1521 1522 // Bit twiddling 1523 1524 /** 1525 * The number of bits used to represent an {@code int} value in two's 1526 * complement binary form. 1527 * 1528 * @since 1.5 1529 */ 1530 @Native public static final int SIZE = 32; 1531 1532 /** 1533 * The number of bytes used to represent a {@code int} value in two's 1534 * complement binary form. 1535 * 1536 * @since 1.8 1537 */ 1538 public static final int BYTES = SIZE / Byte.SIZE; 1539 1540 /** 1541 * Returns an {@code int} value with at most a single one-bit, in the 1542 * position of the highest-order ("leftmost") one-bit in the specified 1543 * {@code int} value. Returns zero if the specified value has no 1544 * one-bits in its two's complement binary representation, that is, if it 1545 * is equal to zero. 1546 * 1547 * @param i the value whose highest one bit is to be computed 1548 * @return an {@code int} value with a single one-bit, in the position 1549 * of the highest-order one-bit in the specified value, or zero if 1550 * the specified value is itself equal to zero. 1551 * @since 1.5 1552 */ 1553 public static int highestOneBit(int i) { 1554 // HD, Figure 3-1 1555 i |= (i >> 1); 1556 i |= (i >> 2); 1557 i |= (i >> 4); 1558 i |= (i >> 8); 1559 i |= (i >> 16); 1560 return i - (i >>> 1); 1561 } 1562 1563 /** 1564 * Returns an {@code int} value with at most a single one-bit, in the 1565 * position of the lowest-order ("rightmost") one-bit in the specified 1566 * {@code int} value. Returns zero if the specified value has no 1567 * one-bits in its two's complement binary representation, that is, if it 1568 * is equal to zero. 1569 * 1570 * @param i the value whose lowest one bit is to be computed 1571 * @return an {@code int} value with a single one-bit, in the position 1572 * of the lowest-order one-bit in the specified value, or zero if 1573 * the specified value is itself equal to zero. 1574 * @since 1.5 1575 */ 1576 public static int lowestOneBit(int i) { 1577 // HD, Section 2-1 1578 return i & -i; 1579 } 1580 1581 /** 1582 * Returns the number of zero bits preceding the highest-order 1583 * ("leftmost") one-bit in the two's complement binary representation 1584 * of the specified {@code int} value. Returns 32 if the 1585 * specified value has no one-bits in its two's complement representation, 1586 * in other words if it is equal to zero. 1587 * 1588 * <p>Note that this method is closely related to the logarithm base 2. 1589 * For all positive {@code int} values x: 1590 * <ul> 1591 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 1592 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 1593 * </ul> 1594 * 1595 * @param i the value whose number of leading zeros is to be computed 1596 * @return the number of zero bits preceding the highest-order 1597 * ("leftmost") one-bit in the two's complement binary representation 1598 * of the specified {@code int} value, or 32 if the value 1599 * is equal to zero. 1600 * @since 1.5 1601 */ 1602 public static int numberOfLeadingZeros(int i) { 1603 // HD, Figure 5-6 1604 if (i == 0) 1605 return 32; 1606 int n = 1; 1607 if (i >>> 16 == 0) { n += 16; i <<= 16; } 1608 if (i >>> 24 == 0) { n += 8; i <<= 8; } 1609 if (i >>> 28 == 0) { n += 4; i <<= 4; } 1610 if (i >>> 30 == 0) { n += 2; i <<= 2; } 1611 n -= i >>> 31; 1612 return n; 1613 } 1614 1615 /** 1616 * Returns the number of zero bits following the lowest-order ("rightmost") 1617 * one-bit in the two's complement binary representation of the specified 1618 * {@code int} value. Returns 32 if the specified value has no 1619 * one-bits in its two's complement representation, in other words if it is 1620 * equal to zero. 1621 * 1622 * @param i the value whose number of trailing zeros is to be computed 1623 * @return the number of zero bits following the lowest-order ("rightmost") 1624 * one-bit in the two's complement binary representation of the 1625 * specified {@code int} value, or 32 if the value is equal 1626 * to zero. 1627 * @since 1.5 1628 */ 1629 public static int numberOfTrailingZeros(int i) { 1630 // HD, Figure 5-14 1631 int y; 1632 if (i == 0) return 32; 1633 int n = 31; 1634 y = i <<16; if (y != 0) { n = n -16; i = y; } 1635 y = i << 8; if (y != 0) { n = n - 8; i = y; } 1636 y = i << 4; if (y != 0) { n = n - 4; i = y; } 1637 y = i << 2; if (y != 0) { n = n - 2; i = y; } 1638 return n - ((i << 1) >>> 31); 1639 } 1640 1641 /** 1642 * Returns the number of one-bits in the two's complement binary 1643 * representation of the specified {@code int} value. This function is 1644 * sometimes referred to as the <i>population count</i>. 1645 * 1646 * @param i the value whose bits are to be counted 1647 * @return the number of one-bits in the two's complement binary 1648 * representation of the specified {@code int} value. 1649 * @since 1.5 1650 */ 1651 public static int bitCount(int i) { 1652 // HD, Figure 5-2 1653 i = i - ((i >>> 1) & 0x55555555); 1654 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); 1655 i = (i + (i >>> 4)) & 0x0f0f0f0f; 1656 i = i + (i >>> 8); 1657 i = i + (i >>> 16); 1658 return i & 0x3f; 1659 } 1660 1661 /** 1662 * Returns the value obtained by rotating the two's complement binary 1663 * representation of the specified {@code int} value left by the 1664 * specified number of bits. (Bits shifted out of the left hand, or 1665 * high-order, side reenter on the right, or low-order.) 1666 * 1667 * <p>Note that left rotation with a negative distance is equivalent to 1668 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1669 * distance)}. Note also that rotation by any multiple of 32 is a 1670 * no-op, so all but the last five bits of the rotation distance can be 1671 * ignored, even if the distance is negative: {@code rotateLeft(val, 1672 * distance) == rotateLeft(val, distance & 0x1F)}. 1673 * 1674 * @param i the value whose bits are to be rotated left 1675 * @param distance the number of bit positions to rotate left 1676 * @return the value obtained by rotating the two's complement binary 1677 * representation of the specified {@code int} value left by the 1678 * specified number of bits. 1679 * @since 1.5 1680 */ 1681 public static int rotateLeft(int i, int distance) { 1682 return (i << distance) | (i >>> -distance); 1683 } 1684 1685 /** 1686 * Returns the value obtained by rotating the two's complement binary 1687 * representation of the specified {@code int} value right by the 1688 * specified number of bits. (Bits shifted out of the right hand, or 1689 * low-order, side reenter on the left, or high-order.) 1690 * 1691 * <p>Note that right rotation with a negative distance is equivalent to 1692 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1693 * distance)}. Note also that rotation by any multiple of 32 is a 1694 * no-op, so all but the last five bits of the rotation distance can be 1695 * ignored, even if the distance is negative: {@code rotateRight(val, 1696 * distance) == rotateRight(val, distance & 0x1F)}. 1697 * 1698 * @param i the value whose bits are to be rotated right 1699 * @param distance the number of bit positions to rotate right 1700 * @return the value obtained by rotating the two's complement binary 1701 * representation of the specified {@code int} value right by the 1702 * specified number of bits. 1703 * @since 1.5 1704 */ 1705 public static int rotateRight(int i, int distance) { 1706 return (i >>> distance) | (i << -distance); 1707 } 1708 1709 /** 1710 * Returns the value obtained by reversing the order of the bits in the 1711 * two's complement binary representation of the specified {@code int} 1712 * value. 1713 * 1714 * @param i the value to be reversed 1715 * @return the value obtained by reversing order of the bits in the 1716 * specified {@code int} value. 1717 * @since 1.5 1718 */ 1719 public static int reverse(int i) { 1720 // HD, Figure 7-1 1721 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; 1722 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; 1723 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; 1724 i = (i << 24) | ((i & 0xff00) << 8) | 1725 ((i >>> 8) & 0xff00) | (i >>> 24); 1726 return i; 1727 } 1728 1729 /** 1730 * Returns the signum function of the specified {@code int} value. (The 1731 * return value is -1 if the specified value is negative; 0 if the 1732 * specified value is zero; and 1 if the specified value is positive.) 1733 * 1734 * @param i the value whose signum is to be computed 1735 * @return the signum function of the specified {@code int} value. 1736 * @since 1.5 1737 */ 1738 public static int signum(int i) { 1739 // HD, Section 2-7 1740 return (i >> 31) | (-i >>> 31); 1741 } 1742 1743 /** 1744 * Returns the value obtained by reversing the order of the bytes in the 1745 * two's complement representation of the specified {@code int} value. 1746 * 1747 * @param i the value whose bytes are to be reversed 1748 * @return the value obtained by reversing the bytes in the specified 1749 * {@code int} value. 1750 * @since 1.5 1751 */ 1752 public static int reverseBytes(int i) { 1753 return ((i >>> 24) ) | 1754 ((i >> 8) & 0xFF00) | 1755 ((i << 8) & 0xFF0000) | 1756 ((i << 24)); 1757 } 1758 1759 /** 1760 * Adds two integers together as per the + operator. 1761 * 1762 * @param a the first operand 1763 * @param b the second operand 1764 * @return the sum of {@code a} and {@code b} 1765 * @see java.util.function.BinaryOperator 1766 * @since 1.8 1767 */ 1768 public static int sum(int a, int b) { 1769 return a + b; 1770 } 1771 1772 /** 1773 * Returns the greater of two {@code int} values 1774 * as if by calling {@link Math#max(int, int) Math.max}. 1775 * 1776 * @param a the first operand 1777 * @param b the second operand 1778 * @return the greater of {@code a} and {@code b} 1779 * @see java.util.function.BinaryOperator 1780 * @since 1.8 1781 */ 1782 public static int max(int a, int b) { 1783 return Math.max(a, b); 1784 } 1785 1786 /** 1787 * Returns the smaller of two {@code int} values 1788 * as if by calling {@link Math#min(int, int) Math.min}. 1789 * 1790 * @param a the first operand 1791 * @param b the second operand 1792 * @return the smaller of {@code a} and {@code b} 1793 * @see java.util.function.BinaryOperator 1794 * @since 1.8 1795 */ 1796 public static int min(int a, int b) { 1797 return Math.min(a, b); 1798 } 1799 1800 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1801 @Native private static final long serialVersionUID = 1360826667806852920L; 1802 }