Integer.java revision 8070af12e129cf6c9c82cf8dd3116aa20a2ebd6d
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.lang;
28
29import java.util.Properties;
30
31/**
32 * The {@code Integer} class wraps a value of the primitive type
33 * {@code int} in an object. An object of type {@code Integer}
34 * contains a single field whose type is {@code int}.
35 *
36 * <p>In addition, this class provides several methods for converting
37 * an {@code int} to a {@code String} and a {@code String} to an
38 * {@code int}, as well as other constants and methods useful when
39 * dealing with an {@code int}.
40 *
41 * <p>Implementation note: The implementations of the "bit twiddling"
42 * methods (such as {@link #highestOneBit(int) highestOneBit} and
43 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
44 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
45 * Delight</i>, (Addison Wesley, 2002).
46 *
47 * @author  Lee Boynton
48 * @author  Arthur van Hoff
49 * @author  Josh Bloch
50 * @author  Joseph D. Darcy
51 * @since JDK1.0
52 */
53public final class Integer extends Number implements Comparable<Integer> {
54    /**
55     * A constant holding the minimum value an {@code int} can
56     * have, -2<sup>31</sup>.
57     */
58    public static final int   MIN_VALUE = 0x80000000;
59
60    /**
61     * A constant holding the maximum value an {@code int} can
62     * have, 2<sup>31</sup>-1.
63     */
64    public static final int   MAX_VALUE = 0x7fffffff;
65
66    /**
67     * The {@code Class} instance representing the primitive type
68     * {@code int}.
69     *
70     * @since   JDK1.1
71     */
72    public static final Class<Integer>  TYPE = (Class<Integer>) int[].class.getComponentType();
73
74    /**
75     * All possible chars for representing a number as a String
76     */
77    final static char[] digits = {
78        '0' , '1' , '2' , '3' , '4' , '5' ,
79        '6' , '7' , '8' , '9' , 'a' , 'b' ,
80        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
81        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
82        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
83        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
84    };
85
86    /**
87     * Returns a string representation of the first argument in the
88     * radix specified by the second argument.
89     *
90     * <p>If the radix is smaller than {@code Character.MIN_RADIX}
91     * or larger than {@code Character.MAX_RADIX}, then the radix
92     * {@code 10} is used instead.
93     *
94     * <p>If the first argument is negative, the first element of the
95     * result is the ASCII minus character {@code '-'}
96     * (<code>'&#92;u002D'</code>). If the first argument is not
97     * negative, no sign character appears in the result.
98     *
99     * <p>The remaining characters of the result represent the magnitude
100     * of the first argument. If the magnitude is zero, it is
101     * represented by a single zero character {@code '0'}
102     * (<code>'&#92;u0030'</code>); otherwise, the first character of
103     * the representation of the magnitude will not be the zero
104     * character.  The following ASCII characters are used as digits:
105     *
106     * <blockquote>
107     *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
108     * </blockquote>
109     *
110     * These are <code>'&#92;u0030'</code> through
111     * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
112     * <code>'&#92;u007A'</code>. If {@code radix} is
113     * <var>N</var>, then the first <var>N</var> of these characters
114     * are used as radix-<var>N</var> digits in the order shown. Thus,
115     * the digits for hexadecimal (radix 16) are
116     * {@code 0123456789abcdef}. If uppercase letters are
117     * desired, the {@link java.lang.String#toUpperCase()} method may
118     * be called on the result:
119     *
120     * <blockquote>
121     *  {@code Integer.toString(n, 16).toUpperCase()}
122     * </blockquote>
123     *
124     * @param   i       an integer to be converted to a string.
125     * @param   radix   the radix to use in the string representation.
126     * @return  a string representation of the argument in the specified radix.
127     * @see     java.lang.Character#MAX_RADIX
128     * @see     java.lang.Character#MIN_RADIX
129     */
130    public static String toString(int i, int radix) {
131
132        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
133            radix = 10;
134
135        /* Use the faster version */
136        if (radix == 10) {
137            return toString(i);
138        }
139
140        char buf[] = new char[33];
141        boolean negative = (i < 0);
142        int charPos = 32;
143
144        if (!negative) {
145            i = -i;
146        }
147
148        while (i <= -radix) {
149            int q = i / radix;
150            buf[charPos--] = digits[radix * q - i];
151            i = q;
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 integer argument as an
164     * unsigned integer in base&nbsp;16.
165     *
166     * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
167     * if the argument is negative; otherwise, it is equal to the
168     * argument.  This value is converted to a string of ASCII digits
169     * in hexadecimal (base&nbsp;16) with no extra leading
170     * {@code 0}s. If the unsigned magnitude is zero, it is
171     * represented by a single zero character {@code '0'}
172     * (<code>'&#92;u0030'</code>); otherwise, the first character of
173     * the representation of the unsigned magnitude will not be the
174     * zero character. The following characters are used as
175     * hexadecimal digits:
176     *
177     * <blockquote>
178     *  {@code 0123456789abcdef}
179     * </blockquote>
180     *
181     * These are the characters <code>'&#92;u0030'</code> through
182     * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
183     * <code>'&#92;u0066'</code>. If uppercase letters are
184     * desired, the {@link java.lang.String#toUpperCase()} method may
185     * be called on the result:
186     *
187     * <blockquote>
188     *  {@code Integer.toHexString(n).toUpperCase()}
189     * </blockquote>
190     *
191     * @param   i   an integer to be converted to a string.
192     * @return  the string representation of the unsigned integer value
193     *          represented by the argument in hexadecimal (base&nbsp;16).
194     * @since   JDK1.0.2
195     */
196    public static String toHexString(int i) {
197        return toUnsignedString(i, 4);
198    }
199
200    /**
201     * Returns a string representation of the integer argument as an
202     * unsigned integer in base&nbsp;8.
203     *
204     * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
205     * if the argument is negative; otherwise, it is equal to the
206     * argument.  This value is converted to a string of ASCII digits
207     * in octal (base&nbsp;8) with no extra leading {@code 0}s.
208     *
209     * <p>If the unsigned magnitude is zero, it is represented by a
210     * single zero character {@code '0'}
211     * (<code>'&#92;u0030'</code>); otherwise, the first character of
212     * the representation of the unsigned magnitude will not be the
213     * zero character. The following characters are used as octal
214     * digits:
215     *
216     * <blockquote>
217     * {@code 01234567}
218     * </blockquote>
219     *
220     * These are the characters <code>'&#92;u0030'</code> through
221     * <code>'&#92;u0037'</code>.
222     *
223     * @param   i   an integer to be converted to a string.
224     * @return  the string representation of the unsigned integer value
225     *          represented by the argument in octal (base&nbsp;8).
226     * @since   JDK1.0.2
227     */
228    public static String toOctalString(int i) {
229        return toUnsignedString(i, 3);
230    }
231
232    /**
233     * Returns a string representation of the integer argument as an
234     * unsigned integer in base&nbsp;2.
235     *
236     * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
237     * if the argument is negative; otherwise it is equal to the
238     * argument.  This value is converted to a string of ASCII digits
239     * in binary (base&nbsp;2) with no extra leading {@code 0}s.
240     * If the unsigned magnitude is zero, it is represented by a
241     * single zero character {@code '0'}
242     * (<code>'&#92;u0030'</code>); otherwise, the first character of
243     * the representation of the unsigned magnitude will not be the
244     * zero character. The characters {@code '0'}
245     * (<code>'&#92;u0030'</code>) and {@code '1'}
246     * (<code>'&#92;u0031'</code>) are used as binary digits.
247     *
248     * @param   i   an integer to be converted to a string.
249     * @return  the string representation of the unsigned integer value
250     *          represented by the argument in binary (base&nbsp;2).
251     * @since   JDK1.0.2
252     */
253    public static String toBinaryString(int i) {
254        return toUnsignedString(i, 1);
255    }
256
257    /**
258     * Convert the integer to an unsigned number.
259     */
260    private static String toUnsignedString(int i, int shift) {
261        char[] buf = new char[32];
262        int charPos = 32;
263        int radix = 1 << shift;
264        int mask = radix - 1;
265        do {
266            buf[--charPos] = digits[i & mask];
267            i >>>= shift;
268        } while (i != 0);
269
270        return new String(buf, charPos, (32 - charPos));
271    }
272
273    private static final String[] SMALL_NEG_VALUES  = new String[100];
274    private static final String[] SMALL_NONNEG_VALUES = new String[100];
275
276    final static char [] DigitTens = {
277        '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
278        '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
279        '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
280        '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
281        '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
282        '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
283        '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
284        '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
285        '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
286        '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
287        } ;
288
289    final static char [] DigitOnes = {
290        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
291        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
292        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
293        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
294        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
295        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
296        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
297        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
298        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
299        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
300        } ;
301
302        // I use the "invariant division by multiplication" trick to
303        // accelerate Integer.toString.  In particular we want to
304        // avoid division by 10.
305        //
306        // The "trick" has roughly the same performance characteristics
307        // as the "classic" Integer.toString code on a non-JIT VM.
308        // The trick avoids .rem and .div calls but has a longer code
309        // path and is thus dominated by dispatch overhead.  In the
310        // JIT case the dispatch overhead doesn't exist and the
311        // "trick" is considerably faster than the classic code.
312        //
313        // TODO-FIXME: convert (x * 52429) into the equiv shift-add
314        // sequence.
315        //
316        // RE:  Division by Invariant Integers using Multiplication
317        //      T Gralund, P Montgomery
318        //      ACM PLDI 1994
319        //
320
321    /**
322     * Returns a {@code String} object representing the
323     * specified integer. The argument is converted to signed decimal
324     * representation and returned as a string, exactly as if the
325     * argument and radix 10 were given as arguments to the {@link
326     * #toString(int, int)} method.
327     *
328     * @param   i   an integer to be converted.
329     * @return  a string representation of the argument in base&nbsp;10.
330     */
331    public static String toString(int i) {
332        if (i == Integer.MIN_VALUE)
333            return "-2147483648";
334
335        // Android-changed: cache the string literal for small values.
336        boolean negative = i < 0;
337        boolean small = negative ? i > -100 : i < 100;
338        if (small) {
339            final String[] smallValues = negative ? SMALL_NEG_VALUES : SMALL_NONNEG_VALUES;
340
341            if (negative) {
342                i = -i;
343                if (smallValues[i] == null) {
344                    smallValues[i] =
345                        i < 10 ? new String(new char[]{'-', DigitOnes[i]})
346                               : new String(new char[]{'-', DigitTens[i], DigitOnes[i]});
347                }
348            } else {
349                if (smallValues[i] == null) {
350                    smallValues[i] =
351                        i < 10 ? new String(new char[]{DigitOnes[i]})
352                               : new String(new char[]{DigitTens[i], DigitOnes[i]});
353                }
354            }
355            return smallValues[i];
356        }
357
358        int size = negative ? stringSize(-i) + 1 : stringSize(i);
359        char[] buf = new char[size];
360        getChars(i, size, buf);
361        // Android-changed: change string constructor.
362        return new String(buf);
363    }
364
365    /**
366     * Places characters representing the integer i into the
367     * character array buf. The characters are placed into
368     * the buffer backwards starting with the least significant
369     * digit at the specified index (exclusive), and working
370     * backwards from there.
371     *
372     * Will fail if i == Integer.MIN_VALUE
373     */
374    static void getChars(int i, int index, char[] buf) {
375        int q, r;
376        int charPos = index;
377        char sign = 0;
378
379        if (i < 0) {
380            sign = '-';
381            i = -i;
382        }
383
384        // Generate two digits per iteration
385        while (i >= 65536) {
386            q = i / 100;
387        // really: r = i - (q * 100);
388            r = i - ((q << 6) + (q << 5) + (q << 2));
389            i = q;
390            buf [--charPos] = DigitOnes[r];
391            buf [--charPos] = DigitTens[r];
392        }
393
394        // Fall thru to fast mode for smaller numbers
395        // assert(i <= 65536, i);
396        for (;;) {
397            q = (i * 52429) >>> (16+3);
398            r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
399            buf [--charPos] = digits [r];
400            i = q;
401            if (i == 0) break;
402        }
403        if (sign != 0) {
404            buf [--charPos] = sign;
405        }
406    }
407
408    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
409                                      99999999, 999999999, Integer.MAX_VALUE };
410
411    // Requires positive x
412    static int stringSize(int x) {
413        for (int i=0; ; i++)
414            if (x <= sizeTable[i])
415                return i+1;
416    }
417
418    /**
419     * Parses the string argument as a signed integer in the radix
420     * specified by the second argument. The characters in the string
421     * must all be digits of the specified radix (as determined by
422     * whether {@link java.lang.Character#digit(char, int)} returns a
423     * nonnegative value), except that the first character may be an
424     * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
425     * indicate a negative value or an ASCII plus sign {@code '+'}
426     * (<code>'&#92;u002B'</code>) to indicate a positive value. The
427     * resulting integer value is returned.
428     *
429     * <p>An exception of type {@code NumberFormatException} is
430     * thrown if any of the following situations occurs:
431     * <ul>
432     * <li>The first argument is {@code null} or is a string of
433     * length zero.
434     *
435     * <li>The radix is either smaller than
436     * {@link java.lang.Character#MIN_RADIX} or
437     * larger than {@link java.lang.Character#MAX_RADIX}.
438     *
439     * <li>Any character of the string is not a digit of the specified
440     * radix, except that the first character may be a minus sign
441     * {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
442     * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
443     * string is longer than length 1.
444     *
445     * <li>The value represented by the string is not a value of type
446     * {@code int}.
447     * </ul>
448     *
449     * <p>Examples:
450     * <blockquote><pre>
451     * parseInt("0", 10) returns 0
452     * parseInt("473", 10) returns 473
453     * parseInt("+42", 10) returns 42
454     * parseInt("-0", 10) returns 0
455     * parseInt("-FF", 16) returns -255
456     * parseInt("1100110", 2) returns 102
457     * parseInt("2147483647", 10) returns 2147483647
458     * parseInt("-2147483648", 10) returns -2147483648
459     * parseInt("2147483648", 10) throws a NumberFormatException
460     * parseInt("99", 8) throws a NumberFormatException
461     * parseInt("Kona", 10) throws a NumberFormatException
462     * parseInt("Kona", 27) returns 411787
463     * </pre></blockquote>
464     *
465     * @param      s   the {@code String} containing the integer
466     *                  representation to be parsed
467     * @param      radix   the radix to be used while parsing {@code s}.
468     * @return     the integer represented by the string argument in the
469     *             specified radix.
470     * @exception  NumberFormatException if the {@code String}
471     *             does not contain a parsable {@code int}.
472     */
473    public static int parseInt(String s, int radix)
474                throws NumberFormatException
475    {
476        /*
477         * WARNING: This method may be invoked early during VM initialization
478         * before IntegerCache is initialized. Care must be taken to not use
479         * the valueOf method.
480         */
481
482        if (s == null) {
483            throw new NumberFormatException("null");
484        }
485
486        if (radix < Character.MIN_RADIX) {
487            throw new NumberFormatException("radix " + radix +
488                                            " less than Character.MIN_RADIX");
489        }
490
491        if (radix > Character.MAX_RADIX) {
492            throw new NumberFormatException("radix " + radix +
493                                            " greater than Character.MAX_RADIX");
494        }
495
496        int result = 0;
497        boolean negative = false;
498        int i = 0, len = s.length();
499        int limit = -Integer.MAX_VALUE;
500        int multmin;
501        int digit;
502
503        if (len > 0) {
504            char firstChar = s.charAt(0);
505            if (firstChar < '0') { // Possible leading "+" or "-"
506                if (firstChar == '-') {
507                    negative = true;
508                    limit = Integer.MIN_VALUE;
509                } else if (firstChar != '+')
510                    throw NumberFormatException.forInputString(s);
511
512                if (len == 1) // Cannot have lone "+" or "-"
513                    throw NumberFormatException.forInputString(s);
514                i++;
515            }
516            multmin = limit / radix;
517            while (i < len) {
518                // Accumulating negatively avoids surprises near MAX_VALUE
519                digit = Character.digit(s.charAt(i++),radix);
520                if (digit < 0) {
521                    throw NumberFormatException.forInputString(s);
522                }
523                if (result < multmin) {
524                    throw NumberFormatException.forInputString(s);
525                }
526                result *= radix;
527                if (result < limit + digit) {
528                    throw NumberFormatException.forInputString(s);
529                }
530                result -= digit;
531            }
532        } else {
533            throw NumberFormatException.forInputString(s);
534        }
535        return negative ? result : -result;
536    }
537
538    /**
539     * Parses the string argument as a signed decimal integer. The
540     * characters in the string must all be decimal digits, except
541     * that the first character may be an ASCII minus sign {@code '-'}
542     * (<code>'&#92;u002D'</code>) to indicate a negative value or an
543     * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
544     * indicate a positive value. The resulting integer value is
545     * returned, exactly as if the argument and the radix 10 were
546     * given as arguments to the {@link #parseInt(java.lang.String,
547     * int)} method.
548     *
549     * @param s    a {@code String} containing the {@code int}
550     *             representation to be parsed
551     * @return     the integer value represented by the argument in decimal.
552     * @exception  NumberFormatException  if the string does not contain a
553     *               parsable integer.
554     */
555    public static int parseInt(String s) throws NumberFormatException {
556        return parseInt(s,10);
557    }
558
559    /**
560     * Returns an {@code Integer} object holding the value
561     * extracted from the specified {@code String} when parsed
562     * with the radix given by the second argument. The first argument
563     * is interpreted as representing a signed integer in the radix
564     * specified by the second argument, exactly as if the arguments
565     * were given to the {@link #parseInt(java.lang.String, int)}
566     * method. The result is an {@code Integer} object that
567     * represents the integer value specified by the string.
568     *
569     * <p>In other words, this method returns an {@code Integer}
570     * object equal to the value of:
571     *
572     * <blockquote>
573     *  {@code new Integer(Integer.parseInt(s, radix))}
574     * </blockquote>
575     *
576     * @param      s   the string to be parsed.
577     * @param      radix the radix to be used in interpreting {@code s}
578     * @return     an {@code Integer} object holding the value
579     *             represented by the string argument in the specified
580     *             radix.
581     * @exception NumberFormatException if the {@code String}
582     *            does not contain a parsable {@code int}.
583     */
584    public static Integer valueOf(String s, int radix) throws NumberFormatException {
585        return Integer.valueOf(parseInt(s,radix));
586    }
587
588    /**
589     * Returns an {@code Integer} object holding the
590     * value of the specified {@code String}. The argument is
591     * interpreted as representing a signed decimal integer, exactly
592     * as if the argument were given to the {@link
593     * #parseInt(java.lang.String)} method. The result is an
594     * {@code Integer} object that represents the integer value
595     * specified by the string.
596     *
597     * <p>In other words, this method returns an {@code Integer}
598     * object equal to the value of:
599     *
600     * <blockquote>
601     *  {@code new Integer(Integer.parseInt(s))}
602     * </blockquote>
603     *
604     * @param      s   the string to be parsed.
605     * @return     an {@code Integer} object holding the value
606     *             represented by the string argument.
607     * @exception  NumberFormatException  if the string cannot be parsed
608     *             as an integer.
609     */
610    public static Integer valueOf(String s) throws NumberFormatException {
611        return Integer.valueOf(parseInt(s, 10));
612    }
613
614    /**
615     * Cache to support the object identity semantics of autoboxing for values between
616     * -128 and 127 (inclusive) as required by JLS.
617     *
618     * The cache is initialized on first usage.  The size of the cache
619     * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
620     * During VM initialization, java.lang.Integer.IntegerCache.high property
621     * may be set and saved in the private system properties in the
622     * sun.misc.VM class.
623     */
624
625    private static class IntegerCache {
626        static final int low = -128;
627        static final int high;
628        static final Integer cache[];
629
630        static {
631            // high value may be configured by property
632            int h = 127;
633            String integerCacheHighPropValue =
634                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
635            if (integerCacheHighPropValue != null) {
636                int i = parseInt(integerCacheHighPropValue);
637                i = Math.max(i, 127);
638                // Maximum array size is Integer.MAX_VALUE
639                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
640            }
641            high = h;
642
643            cache = new Integer[(high - low) + 1];
644            int j = low;
645            for(int k = 0; k < cache.length; k++)
646                cache[k] = new Integer(j++);
647        }
648
649        private IntegerCache() {}
650    }
651
652    /**
653     * Returns an {@code Integer} instance representing the specified
654     * {@code int} value.  If a new {@code Integer} instance is not
655     * required, this method should generally be used in preference to
656     * the constructor {@link #Integer(int)}, as this method is likely
657     * to yield significantly better space and time performance by
658     * caching frequently requested values.
659     *
660     * This method will always cache values in the range -128 to 127,
661     * inclusive, and may cache other values outside of this range.
662     *
663     * @param  i an {@code int} value.
664     * @return an {@code Integer} instance representing {@code i}.
665     * @since  1.5
666     */
667    public static Integer valueOf(int i) {
668        assert IntegerCache.high >= 127;
669        if (i >= IntegerCache.low && i <= IntegerCache.high)
670            return IntegerCache.cache[i + (-IntegerCache.low)];
671        return new Integer(i);
672    }
673
674    /**
675     * The value of the {@code Integer}.
676     *
677     * @serial
678     */
679    private final int value;
680
681    /**
682     * Constructs a newly allocated {@code Integer} object that
683     * represents the specified {@code int} value.
684     *
685     * @param   value   the value to be represented by the
686     *                  {@code Integer} object.
687     */
688    public Integer(int value) {
689        this.value = value;
690    }
691
692    /**
693     * Constructs a newly allocated {@code Integer} object that
694     * represents the {@code int} value indicated by the
695     * {@code String} parameter. The string is converted to an
696     * {@code int} value in exactly the manner used by the
697     * {@code parseInt} method for radix 10.
698     *
699     * @param      s   the {@code String} to be converted to an
700     *                 {@code Integer}.
701     * @exception  NumberFormatException  if the {@code String} does not
702     *               contain a parsable integer.
703     * @see        java.lang.Integer#parseInt(java.lang.String, int)
704     */
705    public Integer(String s) throws NumberFormatException {
706        this.value = parseInt(s, 10);
707    }
708
709    /**
710     * Returns the value of this {@code Integer} as a
711     * {@code byte}.
712     */
713    public byte byteValue() {
714        return (byte)value;
715    }
716
717    /**
718     * Returns the value of this {@code Integer} as a
719     * {@code short}.
720     */
721    public short shortValue() {
722        return (short)value;
723    }
724
725    /**
726     * Returns the value of this {@code Integer} as an
727     * {@code int}.
728     */
729    public int intValue() {
730        return value;
731    }
732
733    /**
734     * Returns the value of this {@code Integer} as a
735     * {@code long}.
736     */
737    public long longValue() {
738        return (long)value;
739    }
740
741    /**
742     * Returns the value of this {@code Integer} as a
743     * {@code float}.
744     */
745    public float floatValue() {
746        return (float)value;
747    }
748
749    /**
750     * Returns the value of this {@code Integer} as a
751     * {@code double}.
752     */
753    public double doubleValue() {
754        return (double)value;
755    }
756
757    /**
758     * Returns a {@code String} object representing this
759     * {@code Integer}'s value. The value is converted to signed
760     * decimal representation and returned as a string, exactly as if
761     * the integer value were given as an argument to the {@link
762     * java.lang.Integer#toString(int)} method.
763     *
764     * @return  a string representation of the value of this object in
765     *          base&nbsp;10.
766     */
767    public String toString() {
768        return toString(value);
769    }
770
771    /**
772     * Returns a hash code for this {@code Integer}.
773     *
774     * @return  a hash code value for this object, equal to the
775     *          primitive {@code int} value represented by this
776     *          {@code Integer} object.
777     */
778    public int hashCode() {
779        return value;
780    }
781
782    /**
783     * Returns a hash code for a {@code int} value; compatible with
784     * {@code Integer.hashCode()}.
785     *
786     * @param value the value to hash
787     * @since 1.8
788     *
789     * @return a hash code value for a {@code int} value.
790     */
791    public static int hashCode(int value) {
792        return value;
793    }
794
795    /**
796     * Compares this object to the specified object.  The result is
797     * {@code true} if and only if the argument is not
798     * {@code null} and is an {@code Integer} object that
799     * contains the same {@code int} value as this object.
800     *
801     * @param   obj   the object to compare with.
802     * @return  {@code true} if the objects are the same;
803     *          {@code false} otherwise.
804     */
805    public boolean equals(Object obj) {
806        if (obj instanceof Integer) {
807            return value == ((Integer)obj).intValue();
808        }
809        return false;
810    }
811
812    /**
813     * Determines the integer value of the system property with the
814     * specified name.
815     *
816     * <p>The first argument is treated as the name of a system property.
817     * System properties are accessible through the
818     * {@link java.lang.System#getProperty(java.lang.String)} method. The
819     * string value of this property is then interpreted as an integer
820     * value and an {@code Integer} object representing this value is
821     * returned. Details of possible numeric formats can be found with
822     * the definition of {@code getProperty}.
823     *
824     * <p>If there is no property with the specified name, if the specified name
825     * is empty or {@code null}, or if the property does not have
826     * the correct numeric format, then {@code null} is returned.
827     *
828     * <p>In other words, this method returns an {@code Integer}
829     * object equal to the value of:
830     *
831     * <blockquote>
832     *  {@code getInteger(nm, null)}
833     * </blockquote>
834     *
835     * @param   nm   property name.
836     * @return  the {@code Integer} value of the property.
837     * @see     java.lang.System#getProperty(java.lang.String)
838     * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
839     */
840    public static Integer getInteger(String nm) {
841        return getInteger(nm, null);
842    }
843
844    /**
845     * Determines the integer value of the system property with the
846     * specified name.
847     *
848     * <p>The first argument is treated as the name of a system property.
849     * System properties are accessible through the {@link
850     * java.lang.System#getProperty(java.lang.String)} method. The
851     * string value of this property is then interpreted as an integer
852     * value and an {@code Integer} object representing this value is
853     * returned. Details of possible numeric formats can be found with
854     * the definition of {@code getProperty}.
855     *
856     * <p>The second argument is the default value. An {@code Integer} object
857     * that represents the value of the second argument is returned if there
858     * is no property of the specified name, if the property does not have
859     * the correct numeric format, or if the specified name is empty or
860     * {@code null}.
861     *
862     * <p>In other words, this method returns an {@code Integer} object
863     * equal to the value of:
864     *
865     * <blockquote>
866     *  {@code getInteger(nm, new Integer(val))}
867     * </blockquote>
868     *
869     * but in practice it may be implemented in a manner such as:
870     *
871     * <blockquote><pre>
872     * Integer result = getInteger(nm, null);
873     * return (result == null) ? new Integer(val) : result;
874     * </pre></blockquote>
875     *
876     * to avoid the unnecessary allocation of an {@code Integer}
877     * object when the default value is not needed.
878     *
879     * @param   nm   property name.
880     * @param   val   default value.
881     * @return  the {@code Integer} value of the property.
882     * @see     java.lang.System#getProperty(java.lang.String)
883     * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
884     */
885    public static Integer getInteger(String nm, int val) {
886        Integer result = getInteger(nm, null);
887        return (result == null) ? Integer.valueOf(val) : result;
888    }
889
890    /**
891     * Returns the integer value of the system property with the
892     * specified name.  The first argument is treated as the name of a
893     * system property.  System properties are accessible through the
894     * {@link java.lang.System#getProperty(java.lang.String)} method.
895     * The string value of this property is then interpreted as an
896     * integer value, as per the {@code Integer.decode} method,
897     * and an {@code Integer} object representing this value is
898     * returned.
899     *
900     * <ul><li>If the property value begins with the two ASCII characters
901     *         {@code 0x} or the ASCII character {@code #}, not
902     *      followed by a minus sign, then the rest of it is parsed as a
903     *      hexadecimal integer exactly as by the method
904     *      {@link #valueOf(java.lang.String, int)} with radix 16.
905     * <li>If the property value begins with the ASCII character
906     *     {@code 0} followed by another character, it is parsed as an
907     *     octal integer exactly as by the method
908     *     {@link #valueOf(java.lang.String, int)} with radix 8.
909     * <li>Otherwise, the property value is parsed as a decimal integer
910     * exactly as by the method {@link #valueOf(java.lang.String, int)}
911     * with radix 10.
912     * </ul>
913     *
914     * <p>The second argument is the default value. The default value is
915     * returned if there is no property of the specified name, if the
916     * property does not have the correct numeric format, or if the
917     * specified name is empty or {@code null}.
918     *
919     * @param   nm   property name.
920     * @param   val   default value.
921     * @return  the {@code Integer} value of the property.
922     * @see     java.lang.System#getProperty(java.lang.String)
923     * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
924     * @see java.lang.Integer#decode
925     */
926    public static Integer getInteger(String nm, Integer val) {
927        String v = null;
928        try {
929            v = System.getProperty(nm);
930        } catch (IllegalArgumentException e) {
931        } catch (NullPointerException e) {
932        }
933        if (v != null) {
934            try {
935                return Integer.decode(v);
936            } catch (NumberFormatException e) {
937            }
938        }
939        return val;
940    }
941
942    /**
943     * Decodes a {@code String} into an {@code Integer}.
944     * Accepts decimal, hexadecimal, and octal numbers given
945     * by the following grammar:
946     *
947     * <blockquote>
948     * <dl>
949     * <dt><i>DecodableString:</i>
950     * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
951     * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
952     * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
953     * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
954     * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
955     * <p>
956     * <dt><i>Sign:</i>
957     * <dd>{@code -}
958     * <dd>{@code +}
959     * </dl>
960     * </blockquote>
961     *
962     * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
963     * are as defined in section 3.10.1 of
964     * <cite>The Java&trade; Language Specification</cite>,
965     * except that underscores are not accepted between digits.
966     *
967     * <p>The sequence of characters following an optional
968     * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
969     * "{@code #}", or leading zero) is parsed as by the {@code
970     * Integer.parseInt} method with the indicated radix (10, 16, or
971     * 8).  This sequence of characters must represent a positive
972     * value or a {@link NumberFormatException} will be thrown.  The
973     * result is negated if first character of the specified {@code
974     * String} is the minus sign.  No whitespace characters are
975     * permitted in the {@code String}.
976     *
977     * @param     nm the {@code String} to decode.
978     * @return    an {@code Integer} object holding the {@code int}
979     *             value represented by {@code nm}
980     * @exception NumberFormatException  if the {@code String} does not
981     *            contain a parsable integer.
982     * @see java.lang.Integer#parseInt(java.lang.String, int)
983     */
984    public static Integer decode(String nm) throws NumberFormatException {
985        int radix = 10;
986        int index = 0;
987        boolean negative = false;
988        Integer result;
989
990        if (nm.length() == 0)
991            throw new NumberFormatException("Zero length string");
992        char firstChar = nm.charAt(0);
993        // Handle sign, if present
994        if (firstChar == '-') {
995            negative = true;
996            index++;
997        } else if (firstChar == '+')
998            index++;
999
1000        // Handle radix specifier, if present
1001        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1002            index += 2;
1003            radix = 16;
1004        }
1005        else if (nm.startsWith("#", index)) {
1006            index ++;
1007            radix = 16;
1008        }
1009        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1010            index ++;
1011            radix = 8;
1012        }
1013
1014        if (nm.startsWith("-", index) || nm.startsWith("+", index))
1015            throw new NumberFormatException("Sign character in wrong position");
1016
1017        try {
1018            result = Integer.valueOf(nm.substring(index), radix);
1019            result = negative ? Integer.valueOf(-result.intValue()) : result;
1020        } catch (NumberFormatException e) {
1021            // If number is Integer.MIN_VALUE, we'll end up here. The next line
1022            // handles this case, and causes any genuine format error to be
1023            // rethrown.
1024            String constant = negative ? ("-" + nm.substring(index))
1025                                       : nm.substring(index);
1026            result = Integer.valueOf(constant, radix);
1027        }
1028        return result;
1029    }
1030
1031    /**
1032     * Compares two {@code Integer} objects numerically.
1033     *
1034     * @param   anotherInteger   the {@code Integer} to be compared.
1035     * @return  the value {@code 0} if this {@code Integer} is
1036     *          equal to the argument {@code Integer}; a value less than
1037     *          {@code 0} if this {@code Integer} is numerically less
1038     *          than the argument {@code Integer}; and a value greater
1039     *          than {@code 0} if this {@code Integer} is numerically
1040     *           greater than the argument {@code Integer} (signed
1041     *           comparison).
1042     * @since   1.2
1043     */
1044    public int compareTo(Integer anotherInteger) {
1045        return compare(this.value, anotherInteger.value);
1046    }
1047
1048    /**
1049     * Compares two {@code int} values numerically.
1050     * The value returned is identical to what would be returned by:
1051     * <pre>
1052     *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
1053     * </pre>
1054     *
1055     * @param  x the first {@code int} to compare
1056     * @param  y the second {@code int} to compare
1057     * @return the value {@code 0} if {@code x == y};
1058     *         a value less than {@code 0} if {@code x < y}; and
1059     *         a value greater than {@code 0} if {@code x > y}
1060     * @since 1.7
1061     */
1062    public static int compare(int x, int y) {
1063        return (x < y) ? -1 : ((x == y) ? 0 : 1);
1064    }
1065
1066
1067    // Bit twiddling
1068
1069    /**
1070     * The number of bits used to represent an {@code int} value in two's
1071     * complement binary form.
1072     *
1073     * @since 1.5
1074     */
1075    public static final int SIZE = 32;
1076
1077
1078    /**
1079     * The number of bytes used to represent a {@code int} value in two's
1080     * complement binary form.
1081     *
1082     * @since 1.8
1083     */
1084    public static final int BYTES = SIZE / Byte.SIZE;
1085
1086    /**
1087     * Returns an {@code int} value with at most a single one-bit, in the
1088     * position of the highest-order ("leftmost") one-bit in the specified
1089     * {@code int} value.  Returns zero if the specified value has no
1090     * one-bits in its two's complement binary representation, that is, if it
1091     * is equal to zero.
1092     *
1093     * @return an {@code int} value with a single one-bit, in the position
1094     *     of the highest-order one-bit in the specified value, or zero if
1095     *     the specified value is itself equal to zero.
1096     * @since 1.5
1097     */
1098    public static int highestOneBit(int i) {
1099        // HD, Figure 3-1
1100        i |= (i >>  1);
1101        i |= (i >>  2);
1102        i |= (i >>  4);
1103        i |= (i >>  8);
1104        i |= (i >> 16);
1105        return i - (i >>> 1);
1106    }
1107
1108    /**
1109     * Returns an {@code int} value with at most a single one-bit, in the
1110     * position of the lowest-order ("rightmost") one-bit in the specified
1111     * {@code int} value.  Returns zero if the specified value has no
1112     * one-bits in its two's complement binary representation, that is, if it
1113     * is equal to zero.
1114     *
1115     * @return an {@code int} value with a single one-bit, in the position
1116     *     of the lowest-order one-bit in the specified value, or zero if
1117     *     the specified value is itself equal to zero.
1118     * @since 1.5
1119     */
1120    public static int lowestOneBit(int i) {
1121        // HD, Section 2-1
1122        return i & -i;
1123    }
1124
1125    /**
1126     * Returns the number of zero bits preceding the highest-order
1127     * ("leftmost") one-bit in the two's complement binary representation
1128     * of the specified {@code int} value.  Returns 32 if the
1129     * specified value has no one-bits in its two's complement representation,
1130     * in other words if it is equal to zero.
1131     *
1132     * <p>Note that this method is closely related to the logarithm base 2.
1133     * For all positive {@code int} values x:
1134     * <ul>
1135     * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1136     * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1137     * </ul>
1138     *
1139     * @return the number of zero bits preceding the highest-order
1140     *     ("leftmost") one-bit in the two's complement binary representation
1141     *     of the specified {@code int} value, or 32 if the value
1142     *     is equal to zero.
1143     * @since 1.5
1144     */
1145    public static int numberOfLeadingZeros(int i) {
1146        // HD, Figure 5-6
1147        if (i == 0)
1148            return 32;
1149        int n = 1;
1150        if (i >>> 16 == 0) { n += 16; i <<= 16; }
1151        if (i >>> 24 == 0) { n +=  8; i <<=  8; }
1152        if (i >>> 28 == 0) { n +=  4; i <<=  4; }
1153        if (i >>> 30 == 0) { n +=  2; i <<=  2; }
1154        n -= i >>> 31;
1155        return n;
1156    }
1157
1158    /**
1159     * Returns the number of zero bits following the lowest-order ("rightmost")
1160     * one-bit in the two's complement binary representation of the specified
1161     * {@code int} value.  Returns 32 if the specified value has no
1162     * one-bits in its two's complement representation, in other words if it is
1163     * equal to zero.
1164     *
1165     * @return the number of zero bits following the lowest-order ("rightmost")
1166     *     one-bit in the two's complement binary representation of the
1167     *     specified {@code int} value, or 32 if the value is equal
1168     *     to zero.
1169     * @since 1.5
1170     */
1171    public static int numberOfTrailingZeros(int i) {
1172        // HD, Figure 5-14
1173        int y;
1174        if (i == 0) return 32;
1175        int n = 31;
1176        y = i <<16; if (y != 0) { n = n -16; i = y; }
1177        y = i << 8; if (y != 0) { n = n - 8; i = y; }
1178        y = i << 4; if (y != 0) { n = n - 4; i = y; }
1179        y = i << 2; if (y != 0) { n = n - 2; i = y; }
1180        return n - ((i << 1) >>> 31);
1181    }
1182
1183    /**
1184     * Returns the number of one-bits in the two's complement binary
1185     * representation of the specified {@code int} value.  This function is
1186     * sometimes referred to as the <i>population count</i>.
1187     *
1188     * @return the number of one-bits in the two's complement binary
1189     *     representation of the specified {@code int} value.
1190     * @since 1.5
1191     */
1192    public static int bitCount(int i) {
1193        // HD, Figure 5-2
1194        i = i - ((i >>> 1) & 0x55555555);
1195        i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1196        i = (i + (i >>> 4)) & 0x0f0f0f0f;
1197        i = i + (i >>> 8);
1198        i = i + (i >>> 16);
1199        return i & 0x3f;
1200    }
1201
1202    /**
1203     * Returns the value obtained by rotating the two's complement binary
1204     * representation of the specified {@code int} value left by the
1205     * specified number of bits.  (Bits shifted out of the left hand, or
1206     * high-order, side reenter on the right, or low-order.)
1207     *
1208     * <p>Note that left rotation with a negative distance is equivalent to
1209     * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1210     * distance)}.  Note also that rotation by any multiple of 32 is a
1211     * no-op, so all but the last five bits of the rotation distance can be
1212     * ignored, even if the distance is negative: {@code rotateLeft(val,
1213     * distance) == rotateLeft(val, distance & 0x1F)}.
1214     *
1215     * @return the value obtained by rotating the two's complement binary
1216     *     representation of the specified {@code int} value left by the
1217     *     specified number of bits.
1218     * @since 1.5
1219     */
1220    public static int rotateLeft(int i, int distance) {
1221        return (i << distance) | (i >>> -distance);
1222    }
1223
1224    /**
1225     * Returns the value obtained by rotating the two's complement binary
1226     * representation of the specified {@code int} value right by the
1227     * specified number of bits.  (Bits shifted out of the right hand, or
1228     * low-order, side reenter on the left, or high-order.)
1229     *
1230     * <p>Note that right rotation with a negative distance is equivalent to
1231     * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1232     * distance)}.  Note also that rotation by any multiple of 32 is a
1233     * no-op, so all but the last five bits of the rotation distance can be
1234     * ignored, even if the distance is negative: {@code rotateRight(val,
1235     * distance) == rotateRight(val, distance & 0x1F)}.
1236     *
1237     * @return the value obtained by rotating the two's complement binary
1238     *     representation of the specified {@code int} value right by the
1239     *     specified number of bits.
1240     * @since 1.5
1241     */
1242    public static int rotateRight(int i, int distance) {
1243        return (i >>> distance) | (i << -distance);
1244    }
1245
1246    /**
1247     * Returns the value obtained by reversing the order of the bits in the
1248     * two's complement binary representation of the specified {@code int}
1249     * value.
1250     *
1251     * @return the value obtained by reversing order of the bits in the
1252     *     specified {@code int} value.
1253     * @since 1.5
1254     */
1255    public static int reverse(int i) {
1256        // HD, Figure 7-1
1257        i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1258        i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1259        i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1260        i = (i << 24) | ((i & 0xff00) << 8) |
1261            ((i >>> 8) & 0xff00) | (i >>> 24);
1262        return i;
1263    }
1264
1265    /**
1266     * Returns the signum function of the specified {@code int} value.  (The
1267     * return value is -1 if the specified value is negative; 0 if the
1268     * specified value is zero; and 1 if the specified value is positive.)
1269     *
1270     * @return the signum function of the specified {@code int} value.
1271     * @since 1.5
1272     */
1273    public static int signum(int i) {
1274        // HD, Section 2-7
1275        return (i >> 31) | (-i >>> 31);
1276    }
1277
1278    /**
1279     * Returns the value obtained by reversing the order of the bytes in the
1280     * two's complement representation of the specified {@code int} value.
1281     *
1282     * @return the value obtained by reversing the bytes in the specified
1283     *     {@code int} value.
1284     * @since 1.5
1285     */
1286    public static int reverseBytes(int i) {
1287        return ((i >>> 24)           ) |
1288               ((i >>   8) &   0xFF00) |
1289               ((i <<   8) & 0xFF0000) |
1290               ((i << 24));
1291    }
1292
1293    /**
1294     * Adds two integers together as per the + operator.
1295     *
1296     * @param a the first operand
1297     * @param b the second operand
1298     * @return the sum of {@code a} and {@code b}
1299     * @see java.util.function.BinaryOperator
1300     * @since 1.8
1301     */
1302    public static int sum(int a, int b) {
1303        return a + b;
1304    }
1305
1306    /**
1307     * Returns the greater of two {@code int} values
1308     * as if by calling {@link Math#max(int, int) Math.max}.
1309     *
1310     * @param a the first operand
1311     * @param b the second operand
1312     * @return the greater of {@code a} and {@code b}
1313     * @see java.util.function.BinaryOperator
1314     * @since 1.8
1315     */
1316    public static int max(int a, int b) {
1317        return Math.max(a, b);
1318    }
1319
1320    /**
1321     * Returns the smaller of two {@code int} values
1322     * as if by calling {@link Math#min(int, int) Math.min}.
1323     *
1324     * @param a the first operand
1325     * @param b the second operand
1326     * @return the smaller of {@code a} and {@code b}
1327     * @see java.util.function.BinaryOperator
1328     * @since 1.8
1329     */
1330    public static int min(int a, int b) {
1331        return Math.min(a, b);
1332    }
1333
1334    /** use serialVersionUID from JDK 1.0.2 for interoperability */
1335    private static final long serialVersionUID = 1360826667806852920L;
1336}
1337