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