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