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