1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package java.lang;
19
20/**
21 * The wrapper for the primitive type {@code int}.
22 * <p>
23 * Implementation note: The "bit twiddling" methods in this class use techniques
24 * described in <a href="http://www.hackersdelight.org/">Henry S. Warren,
25 * Jr.'s Hacker's Delight, (Addison Wesley, 2002)</a> and <a href=
26 * "http://graphics.stanford.edu/~seander/bithacks.html">Sean Anderson's
27 * Bit Twiddling Hacks.</a>
28 *
29 * @see java.lang.Long
30 * @since 1.0
31 */
32@FindBugsSuppressWarnings("DM_NUMBER_CTOR")
33public final class Integer extends Number implements Comparable<Integer> {
34
35    private static final long serialVersionUID = 1360826667806852920L;
36
37    /**
38     * The int value represented by this Integer
39     */
40    private final int value;
41
42    /**
43     * Constant for the maximum {@code int} value, 2<sup>31</sup>-1.
44     */
45    public static final int MAX_VALUE = 0x7FFFFFFF;
46
47    /**
48     * Constant for the minimum {@code int} value, -2<sup>31</sup>.
49     */
50    public static final int MIN_VALUE = 0x80000000;
51
52    /**
53     * Constant for the number of bits needed to represent an {@code int} in
54     * two's complement form.
55     *
56     * @since 1.5
57     */
58    public static final int SIZE = 32;
59
60    /**
61     * Table for Seal's algorithm for Number of Trailing Zeros. Hacker's Delight
62     * online, Figure 5-18 (http://www.hackersdelight.org/revisions.pdf)
63     * The entries whose value is -1 are never referenced.
64     */
65    private static final byte[] NTZ_TABLE = {
66        32,  0,  1, 12,  2,  6, -1, 13,   3, -1,  7, -1, -1, -1, -1, 14,
67        10,  4, -1, -1,  8, -1, -1, 25,  -1, -1, -1, -1, -1, 21, 27, 15,
68        31, 11,  5, -1, -1, -1, -1, -1,   9, -1, -1, 24, -1, -1, 20, 26,
69        30, -1, -1, -1, -1, 23, -1, 19,  29, -1, 22, 18, 28, 17, 16, -1
70    };
71
72    /**
73     * The {@link Class} object that represents the primitive type {@code int}.
74     */
75    @SuppressWarnings("unchecked")
76    public static final Class<Integer> TYPE
77            = (Class<Integer>) int[].class.getComponentType();
78    // Note: Integer.TYPE can't be set to "int.class", since *that* is
79    // defined to be "java.lang.Integer.TYPE";
80
81    /**
82     * Constructs a new {@code Integer} with the specified primitive integer
83     * value.
84     *
85     * @param value
86     *            the primitive integer value to store in the new instance.
87     */
88    public Integer(int value) {
89        this.value = value;
90    }
91
92    /**
93     * Constructs a new {@code Integer} from the specified string.
94     *
95     * @param string
96     *            the string representation of an integer value.
97     * @throws NumberFormatException
98     *             if {@code string} cannot be parsed as an integer value.
99     * @see #parseInt(String)
100     */
101    public Integer(String string) throws NumberFormatException {
102        this(parseInt(string));
103    }
104
105    @Override
106    public byte byteValue() {
107        return (byte) value;
108    }
109
110    /**
111     * Compares this object to the specified integer object to determine their
112     * relative order.
113     *
114     * @param object
115     *            the integer object to compare this object to.
116     * @return a negative value if the value of this integer is less than the
117     *         value of {@code object}; 0 if the value of this integer and the
118     *         value of {@code object} are equal; a positive value if the value
119     *         of this integer is greater than the value of {@code object}.
120     * @see java.lang.Comparable
121     * @since 1.2
122     */
123    public int compareTo(Integer object) {
124        return compare(value, object.value);
125    }
126
127    /**
128     * Compares two {@code int} values.
129     * @return 0 if lhs = rhs, less than 0 if lhs &lt; rhs, and greater than 0 if lhs &gt; rhs.
130     * @since 1.7
131     */
132    public static int compare(int lhs, int rhs) {
133        return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
134    }
135
136    private static NumberFormatException invalidInt(String s) {
137        throw new NumberFormatException("Invalid int: \"" + s + "\"");
138    }
139
140    /**
141     * Parses the specified string and returns a {@code Integer} instance if the
142     * string can be decoded into an integer value. The string may be an
143     * optional minus sign "-" followed by a hexadecimal ("0x..." or "#..."),
144     * octal ("0..."), or decimal ("...") representation of an integer.
145     *
146     * @param string
147     *            a string representation of an integer value.
148     * @return an {@code Integer} containing the value represented by
149     *         {@code string}.
150     * @throws NumberFormatException
151     *             if {@code string} cannot be parsed as an integer value.
152     */
153    public static Integer decode(String string) throws NumberFormatException {
154        int length = string.length(), i = 0;
155        if (length == 0) {
156            throw invalidInt(string);
157        }
158        char firstDigit = string.charAt(i);
159        boolean negative = firstDigit == '-';
160        if (negative) {
161            if (length == 1) {
162                throw invalidInt(string);
163            }
164            firstDigit = string.charAt(++i);
165        }
166
167        int base = 10;
168        if (firstDigit == '0') {
169            if (++i == length) {
170                return valueOf(0);
171            }
172            if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') {
173                if (++i == length) {
174                    throw invalidInt(string);
175                }
176                base = 16;
177            } else {
178                base = 8;
179            }
180        } else if (firstDigit == '#') {
181            if (++i == length) {
182                throw invalidInt(string);
183            }
184            base = 16;
185        }
186
187        int result = parse(string, i, base, negative);
188        return valueOf(result);
189    }
190
191    @Override
192    public double doubleValue() {
193        return value;
194    }
195
196    /**
197     * Compares this instance with the specified object and indicates if they
198     * are equal. In order to be equal, {@code o} must be an instance of
199     * {@code Integer} and have the same integer value as this object.
200     *
201     * @param o
202     *            the object to compare this integer with.
203     * @return {@code true} if the specified object is equal to this
204     *         {@code Integer}; {@code false} otherwise.
205     */
206    @Override
207    public boolean equals(Object o) {
208        return (o instanceof Integer) && (((Integer) o).value == value);
209    }
210
211    @Override
212    public float floatValue() {
213        return value;
214    }
215
216    /**
217     * Returns the {@code Integer} value of the system property identified by
218     * {@code string}. Returns {@code null} if {@code string} is {@code null}
219     * or empty, if the property can not be found or if its value can not be
220     * parsed as an integer.
221     *
222     * @param string
223     *            the name of the requested system property.
224     * @return the requested property's value as an {@code Integer} or
225     *         {@code null}.
226     */
227    public static Integer getInteger(String string) {
228        if (string == null || string.length() == 0) {
229            return null;
230        }
231        String prop = System.getProperty(string);
232        if (prop == null) {
233            return null;
234        }
235        try {
236            return decode(prop);
237        } catch (NumberFormatException ex) {
238            return null;
239        }
240    }
241
242    /**
243     * Returns the {@code Integer} value of the system property identified by
244     * {@code string}. Returns the specified default value if {@code string} is
245     * {@code null} or empty, if the property can not be found or if its value
246     * can not be parsed as an integer.
247     *
248     * @param string
249     *            the name of the requested system property.
250     * @param defaultValue
251     *            the default value that is returned if there is no integer
252     *            system property with the requested name.
253     * @return the requested property's value as an {@code Integer} or the
254     *         default value.
255     */
256    public static Integer getInteger(String string, int defaultValue) {
257        if (string == null || string.length() == 0) {
258            return valueOf(defaultValue);
259        }
260        String prop = System.getProperty(string);
261        if (prop == null) {
262            return valueOf(defaultValue);
263        }
264        try {
265            return decode(prop);
266        } catch (NumberFormatException ex) {
267            return valueOf(defaultValue);
268        }
269    }
270
271    /**
272     * Returns the {@code Integer} value of the system property identified by
273     * {@code string}. Returns the specified default value if {@code string} is
274     * {@code null} or empty, if the property can not be found or if its value
275     * can not be parsed as an integer.
276     *
277     * @param string
278     *            the name of the requested system property.
279     * @param defaultValue
280     *            the default value that is returned if there is no integer
281     *            system property with the requested name.
282     * @return the requested property's value as an {@code Integer} or the
283     *         default value.
284     */
285    public static Integer getInteger(String string, Integer defaultValue) {
286        if (string == null || string.length() == 0) {
287            return defaultValue;
288        }
289        String prop = System.getProperty(string);
290        if (prop == null) {
291            return defaultValue;
292        }
293        try {
294            return decode(prop);
295        } catch (NumberFormatException ex) {
296            return defaultValue;
297        }
298    }
299
300    @Override
301    public int hashCode() {
302        return value;
303    }
304
305    /**
306     * Gets the primitive value of this int.
307     *
308     * @return this object's primitive value.
309     */
310    @Override
311    public int intValue() {
312        return value;
313    }
314
315    @Override
316    public long longValue() {
317        return value;
318    }
319
320    /**
321     * Parses the specified string as a signed decimal integer value. The ASCII
322     * character \u002d ('-') is recognized as the minus sign.
323     *
324     * @param string
325     *            the string representation of an integer value.
326     * @return the primitive integer value represented by {@code string}.
327     * @throws NumberFormatException
328     *             if {@code string} cannot be parsed as an integer value.
329     */
330    public static int parseInt(String string) throws NumberFormatException {
331        return parseInt(string, 10);
332    }
333
334    /**
335     * Parses the specified string as a signed integer value using the specified
336     * radix. The ASCII character \u002d ('-') is recognized as the minus sign.
337     *
338     * @param string
339     *            the string representation of an integer value.
340     * @param radix
341     *            the radix to use when parsing.
342     * @return the primitive integer value represented by {@code string} using
343     *         {@code radix}.
344     * @throws NumberFormatException
345     *             if {@code string} cannot be parsed as an integer value,
346     *             or {@code radix < Character.MIN_RADIX ||
347     *             radix > Character.MAX_RADIX}.
348     */
349    public static int parseInt(String string, int radix) throws NumberFormatException {
350        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
351            throw new NumberFormatException("Invalid radix: " + radix);
352        }
353        if (string == null) {
354            throw invalidInt(string);
355        }
356        int length = string.length(), i = 0;
357        if (length == 0) {
358            throw invalidInt(string);
359        }
360        boolean negative = string.charAt(i) == '-';
361        if (negative && ++i == length) {
362            throw invalidInt(string);
363        }
364
365        return parse(string, i, radix, negative);
366    }
367
368    private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {
369        int max = Integer.MIN_VALUE / radix;
370        int result = 0, length = string.length();
371        while (offset < length) {
372            int digit = Character.digit(string.charAt(offset++), radix);
373            if (digit == -1) {
374                throw invalidInt(string);
375            }
376            if (max > result) {
377                throw invalidInt(string);
378            }
379            int next = result * radix - digit;
380            if (next > result) {
381                throw invalidInt(string);
382            }
383            result = next;
384        }
385        if (!negative) {
386            result = -result;
387            if (result < 0) {
388                throw invalidInt(string);
389            }
390        }
391        return result;
392    }
393
394    @Override
395    public short shortValue() {
396        return (short) value;
397    }
398
399    /**
400     * Converts the specified integer into its binary string representation. The
401     * returned string is a concatenation of '0' and '1' characters.
402     *
403     * @param i
404     *            the integer to convert.
405     * @return the binary string representation of {@code i}.
406     */
407    public static String toBinaryString(int i) {
408        return IntegralToString.intToBinaryString(i);
409    }
410
411    /**
412     * Converts the specified integer into its hexadecimal string
413     * representation. The returned string is a concatenation of characters from
414     * '0' to '9' and 'a' to 'f'.
415     *
416     * @param i
417     *            the integer to convert.
418     * @return the hexadecimal string representation of {@code i}.
419     */
420    public static String toHexString(int i) {
421        return IntegralToString.intToHexString(i, false, 0);
422    }
423
424    /**
425     * Converts the specified integer into its octal string representation. The
426     * returned string is a concatenation of characters from '0' to '7'.
427     *
428     * @param i
429     *            the integer to convert.
430     * @return the octal string representation of {@code i}.
431     */
432    public static String toOctalString(int i) {
433        return IntegralToString.intToOctalString(i);
434    }
435
436    @Override
437    public String toString() {
438        return Integer.toString(value);
439    }
440
441    /**
442     * Converts the specified integer into its decimal string representation.
443     * The returned string is a concatenation of a minus sign if the number is
444     * negative and characters from '0' to '9'.
445     *
446     * @param i
447     *            the integer to convert.
448     * @return the decimal string representation of {@code i}.
449     */
450    public static String toString(int i) {
451        return IntegralToString.intToString(i);
452    }
453
454    /**
455     * Converts the specified signed integer into a string representation based on the
456     * specified radix. The returned string is a concatenation of a minus sign
457     * if the number is negative and characters from '0' to '9' and 'a' to 'z',
458     * depending on the radix. If {@code radix} is not in the interval defined
459     * by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX} then 10 is
460     * used as the base for the conversion.
461     *
462     * <p>This method treats its argument as signed. If you want to convert an
463     * unsigned value to one of the common non-decimal bases, you may find
464     * {@link #toBinaryString}, {@code #toHexString}, or {@link #toOctalString}
465     * more convenient.
466     *
467     * @param i
468     *            the signed integer to convert.
469     * @param radix
470     *            the base to use for the conversion.
471     * @return the string representation of {@code i}.
472     */
473    public static String toString(int i, int radix) {
474        return IntegralToString.intToString(i, radix);
475    }
476
477    /**
478     * Parses the specified string as a signed decimal integer value.
479     *
480     * @param string
481     *            the string representation of an integer value.
482     * @return an {@code Integer} instance containing the integer value
483     *         represented by {@code string}.
484     * @throws NumberFormatException
485     *             if {@code string} cannot be parsed as an integer value.
486     * @see #parseInt(String)
487     */
488    public static Integer valueOf(String string) throws NumberFormatException {
489        return valueOf(parseInt(string));
490    }
491
492    /**
493     * Parses the specified string as a signed integer value using the specified
494     * radix.
495     *
496     * @param string
497     *            the string representation of an integer value.
498     * @param radix
499     *            the radix to use when parsing.
500     * @return an {@code Integer} instance containing the integer value
501     *         represented by {@code string} using {@code radix}.
502     * @throws NumberFormatException
503     *             if {@code string} cannot be parsed as an integer value, or
504     *             {@code radix < Character.MIN_RADIX ||
505     *             radix > Character.MAX_RADIX}.
506     * @see #parseInt(String, int)
507     */
508    public static Integer valueOf(String string, int radix) throws NumberFormatException {
509        return valueOf(parseInt(string, radix));
510    }
511
512    /**
513     * Determines the highest (leftmost) bit of the specified integer that is 1
514     * and returns the bit mask value for that bit. This is also referred to as
515     * the Most Significant 1 Bit. Returns zero if the specified integer is
516     * zero.
517     *
518     * @param i
519     *            the integer to examine.
520     * @return the bit mask indicating the highest 1 bit in {@code i}.
521     * @since 1.5
522     */
523    public static int highestOneBit(int i) {
524        // Hacker's Delight, Figure 3-1
525        i |= (i >> 1);
526        i |= (i >> 2);
527        i |= (i >> 4);
528        i |= (i >> 8);
529        i |= (i >> 16);
530        return i - (i >>> 1);
531    }
532
533    /**
534     * Determines the lowest (rightmost) bit of the specified integer that is 1
535     * and returns the bit mask value for that bit. This is also referred
536     * to as the Least Significant 1 Bit. Returns zero if the specified integer
537     * is zero.
538     *
539     * @param i
540     *            the integer to examine.
541     * @return the bit mask indicating the lowest 1 bit in {@code i}.
542     * @since 1.5
543     */
544    public static int lowestOneBit(int i) {
545        return i & -i;
546    }
547
548    /**
549     * Determines the number of leading zeros in the specified integer prior to
550     * the {@link #highestOneBit(int) highest one bit}.
551     *
552     * @param i
553     *            the integer to examine.
554     * @return the number of leading zeros in {@code i}.
555     * @since 1.5
556     */
557    public static int numberOfLeadingZeros(int i) {
558        // Hacker's Delight, Figure 5-6
559        if (i <= 0) {
560            return (~i >> 26) & 32;
561        }
562        int n = 1;
563        if (i >> 16 == 0) {
564            n +=  16;
565            i <<= 16;
566        }
567        if (i >> 24 == 0) {
568            n +=  8;
569            i <<= 8;
570        }
571        if (i >> 28 == 0) {
572            n +=  4;
573            i <<= 4;
574        }
575        if (i >> 30 == 0) {
576            n +=  2;
577            i <<= 2;
578        }
579        return n - (i >>> 31);
580    }
581
582    /**
583     * Determines the number of trailing zeros in the specified integer after
584     * the {@link #lowestOneBit(int) lowest one bit}.
585     *
586     * @param i
587     *            the integer to examine.
588     * @return the number of trailing zeros in {@code i}.
589     * @since 1.5
590     */
591    public static int numberOfTrailingZeros(int i) {
592        return NTZ_TABLE[((i & -i) * 0x0450FBAF) >>> 26];
593    }
594
595    /**
596     * Counts the number of 1 bits in the specified integer; this is also
597     * referred to as population count.
598     *
599     * @param i
600     *            the integer to examine.
601     * @return the number of 1 bits in {@code i}.
602     * @since 1.5
603     */
604    public static int bitCount(int i) {
605        // Hacker's Delight, Figure 5-2
606        i -= (i >> 1) & 0x55555555;
607        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
608        i = ((i >> 4) + i) & 0x0F0F0F0F;
609        i += i >> 8;
610        i += i >> 16;
611        return i & 0x0000003F;
612    }
613
614    /**
615     * Rotates the bits of the specified integer to the left by the specified
616     * number of bits.
617     *
618     * @param i
619     *            the integer value to rotate left.
620     * @param distance
621     *            the number of bits to rotate.
622     * @return the rotated value.
623     * @since 1.5
624     */
625    public static int rotateLeft(int i, int distance) {
626        // Shift distances are mod 32 (JLS3 15.19), so we needn't mask -distance
627        return (i << distance) | (i >>> -distance);
628    }
629
630    /**
631     * Rotates the bits of the specified integer to the right by the specified
632     * number of bits.
633     *
634     * @param i
635     *            the integer value to rotate right.
636     * @param distance
637     *            the number of bits to rotate.
638     * @return the rotated value.
639     * @since 1.5
640     */
641    public static int rotateRight(int i, int distance) {
642        // Shift distances are mod 32 (JLS3 15.19), so we needn't mask -distance
643        return (i >>> distance) | (i << -distance);
644    }
645
646    /**
647     * Reverses the order of the bytes of the specified integer.
648     *
649     * @param i
650     *            the integer value for which to reverse the byte order.
651     * @return the reversed value.
652     * @since 1.5
653     */
654    public static int reverseBytes(int i) {
655        // Hacker's Delight 7-1, with minor tweak from Veldmeijer
656        // http://graphics.stanford.edu/~seander/bithacks.html
657        i =    ((i >>>  8) & 0x00FF00FF) | ((i & 0x00FF00FF) <<  8);
658        return ( i >>> 16              ) | ( i               << 16);
659    }
660
661    /**
662     * Reverses the order of the bits of the specified integer.
663     *
664     * @param i
665     *            the integer value for which to reverse the bit order.
666     * @return the reversed value.
667     * @since 1.5
668     */
669    public static int reverse(int i) {
670        // Hacker's Delight 7-1, with minor tweak from Veldmeijer
671        // http://graphics.stanford.edu/~seander/bithacks.html
672        i =    ((i >>>  1) & 0x55555555) | ((i & 0x55555555) <<  1);
673        i =    ((i >>>  2) & 0x33333333) | ((i & 0x33333333) <<  2);
674        i =    ((i >>>  4) & 0x0F0F0F0F) | ((i & 0x0F0F0F0F) <<  4);
675        i =    ((i >>>  8) & 0x00FF00FF) | ((i & 0x00FF00FF) <<  8);
676        return ((i >>> 16)             ) | ((i             ) << 16);
677    }
678
679    /**
680     * Returns the value of the {@code signum} function for the specified
681     * integer.
682     *
683     * @param i
684     *            the integer value to check.
685     * @return -1 if {@code i} is negative, 1 if {@code i} is positive, 0 if
686     *         {@code i} is zero.
687     * @since 1.5
688     */
689    public static int signum(int i) {
690        return (i >> 31) | (-i >>> 31); // Hacker's delight 2-7
691    }
692
693    /**
694     * Returns a {@code Integer} instance for the specified integer value.
695     * <p>
696     * If it is not necessary to get a new {@code Integer} instance, it is
697     * recommended to use this method instead of the constructor, since it
698     * maintains a cache of instances which may result in better performance.
699     *
700     * @param i
701     *            the integer value to store in the instance.
702     * @return a {@code Integer} instance containing {@code i}.
703     * @since 1.5
704     */
705    public static Integer valueOf(int i) {
706        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
707    }
708
709    /**
710     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
711     */
712    private static final Integer[] SMALL_VALUES = new Integer[256];
713
714    static {
715        for (int i = -128; i < 128; i++) {
716            SMALL_VALUES[i + 128] = new Integer(i);
717        }
718    }
719}
720