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