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