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