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.
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.
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).
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.
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
28 import java.util.Properties;
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}.
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}.
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).
47 * @author Arthur van Hoff
49 * @author Joseph D. Darcy
52 public final class Integer extends Number implements Comparable<Integer> {
54 * A constant holding the minimum value an {@code int} can
55 * have, -2<sup>31</sup>.
57 public static final int MIN_VALUE = 0x80000000;
60 * A constant holding the maximum value an {@code int} can
61 * have, 2<sup>31</sup>-1.
63 public static final int MAX_VALUE = 0x7fffffff;
66 * The {@code Class} instance representing the primitive type
71 public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
74 * All possible chars for representing a number as a String
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'
86 * Returns a string representation of the first argument in the
87 * radix specified by the second argument.
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.
93 * <p>If the first argument is negative, the first element of the
94 * result is the ASCII minus character {@code '-'}
95 * (<code>'\u002D'</code>). If the first argument is not
96 * negative, no sign character appears in the result.
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>'\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:
106 * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
109 * These are <code>'\u0030'</code> through
110 * <code>'\u0039'</code> and <code>'\u0061'</code> through
111 * <code>'\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:
120 * {@code Integer.toString(n, 16).toUpperCase()}
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
129 public static String toString(int i, int radix) {
131 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
134 /* Use the faster version */
139 char buf[] = new char[33];
140 boolean negative = (i < 0);
147 while (i <= -radix) {
148 buf[charPos--] = digits[-(i % radix)];
151 buf[charPos] = digits[-i];
154 buf[--charPos] = '-';
157 return new String(buf, charPos, (33 - charPos));
161 * Returns a string representation of the integer argument as an
162 * unsigned integer in base 16.
164 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
165 * if the argument is negative; otherwise, it is equal to the
166 * argument. This value is converted to a string of ASCII digits
167 * in hexadecimal (base 16) with no extra leading
168 * {@code 0}s. If the unsigned magnitude is zero, it is
169 * represented by a single zero character {@code '0'}
170 * (<code>'\u0030'</code>); otherwise, the first character of
171 * the representation of the unsigned magnitude will not be the
172 * zero character. The following characters are used as
173 * hexadecimal digits:
176 * {@code 0123456789abcdef}
179 * These are the characters <code>'\u0030'</code> through
180 * <code>'\u0039'</code> and <code>'\u0061'</code> through
181 * <code>'\u0066'</code>. If uppercase letters are
182 * desired, the {@link java.lang.String#toUpperCase()} method may
183 * be called on the result:
186 * {@code Integer.toHexString(n).toUpperCase()}
189 * @param i an integer to be converted to a string.
190 * @return the string representation of the unsigned integer value
191 * represented by the argument in hexadecimal (base 16).
194 public static String toHexString(int i) {
195 return toUnsignedString(i, 4);
199 * Returns a string representation of the integer argument as an
200 * unsigned integer in base 8.
202 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
203 * if the argument is negative; otherwise, it is equal to the
204 * argument. This value is converted to a string of ASCII digits
205 * in octal (base 8) with no extra leading {@code 0}s.
207 * <p>If the unsigned magnitude is zero, it is represented by a
208 * single zero character {@code '0'}
209 * (<code>'\u0030'</code>); otherwise, the first character of
210 * the representation of the unsigned magnitude will not be the
211 * zero character. The following characters are used as octal
218 * These are the characters <code>'\u0030'</code> through
219 * <code>'\u0037'</code>.
221 * @param i an integer to be converted to a string.
222 * @return the string representation of the unsigned integer value
223 * represented by the argument in octal (base 8).
226 public static String toOctalString(int i) {
227 return toUnsignedString(i, 3);
231 * Returns a string representation of the integer argument as an
232 * unsigned integer in base 2.
234 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
235 * if the argument is negative; otherwise it is equal to the
236 * argument. This value is converted to a string of ASCII digits
237 * in binary (base 2) with no extra leading {@code 0}s.
238 * If the unsigned magnitude is zero, it is represented by a
239 * single zero character {@code '0'}
240 * (<code>'\u0030'</code>); otherwise, the first character of
241 * the representation of the unsigned magnitude will not be the
242 * zero character. The characters {@code '0'}
243 * (<code>'\u0030'</code>) and {@code '1'}
244 * (<code>'\u0031'</code>) are used as binary digits.
246 * @param i an integer to be converted to a string.
247 * @return the string representation of the unsigned integer value
248 * represented by the argument in binary (base 2).
251 public static String toBinaryString(int i) {
252 return toUnsignedString(i, 1);
256 * Convert the integer to an unsigned number.
258 private static String toUnsignedString(int i, int shift) {
259 char[] buf = new char[32];
261 int radix = 1 << shift;
262 int mask = radix - 1;
264 buf[--charPos] = digits[i & mask];
268 return new String(buf, charPos, (32 - charPos));
272 final static char [] DigitTens = {
273 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
274 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
275 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
276 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
277 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
278 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
279 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
280 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
281 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
282 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
285 final static char [] DigitOnes = {
286 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
287 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
288 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
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',
298 // I use the "invariant division by multiplication" trick to
299 // accelerate Integer.toString. In particular we want to
300 // avoid division by 10.
302 // The "trick" has roughly the same performance characteristics
303 // as the "classic" Integer.toString code on a non-JIT VM.
304 // The trick avoids .rem and .div calls but has a longer code
305 // path and is thus dominated by dispatch overhead. In the
306 // JIT case the dispatch overhead doesn't exist and the
307 // "trick" is considerably faster than the classic code.
309 // TODO-FIXME: convert (x * 52429) into the equiv shift-add
312 // RE: Division by Invariant Integers using Multiplication
313 // T Gralund, P Montgomery
318 * Returns a {@code String} object representing the
319 * specified integer. The argument is converted to signed decimal
320 * representation and returned as a string, exactly as if the
321 * argument and radix 10 were given as arguments to the {@link
322 * #toString(int, int)} method.
324 * @param i an integer to be converted.
325 * @return a string representation of the argument in base 10.
327 public static String toString(int i) {
328 if (i == Integer.MIN_VALUE)
329 return "-2147483648";
330 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
331 char[] buf = new char[size];
332 getChars(i, size, buf);
333 return new String(0, size, buf);
337 * Places characters representing the integer i into the
338 * character array buf. The characters are placed into
339 * the buffer backwards starting with the least significant
340 * digit at the specified index (exclusive), and working
341 * backwards from there.
343 * Will fail if i == Integer.MIN_VALUE
345 static void getChars(int i, int index, char[] buf) {
355 // Generate two digits per iteration
358 // really: r = i - (q * 100);
359 r = i - ((q << 6) + (q << 5) + (q << 2));
361 buf [--charPos] = DigitOnes[r];
362 buf [--charPos] = DigitTens[r];
365 // Fall thru to fast mode for smaller numbers
366 // assert(i <= 65536, i);
368 q = (i * 52429) >>> (16+3);
369 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
370 buf [--charPos] = digits [r];
375 buf [--charPos] = sign;
379 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
380 99999999, 999999999, Integer.MAX_VALUE };
382 // Requires positive x
383 static int stringSize(int x) {
385 if (x <= sizeTable[i])
390 * Parses the string argument as a signed integer in the radix
391 * specified by the second argument. The characters in the string
392 * must all be digits of the specified radix (as determined by
393 * whether {@link java.lang.Character#digit(char, int)} returns a
394 * nonnegative value), except that the first character may be an
395 * ASCII minus sign {@code '-'} (<code>'\u002D'</code>) to
396 * indicate a negative value or an ASCII plus sign {@code '+'}
397 * (<code>'\u002B'</code>) to indicate a positive value. The
398 * resulting integer value is returned.
400 * <p>An exception of type {@code NumberFormatException} is
401 * thrown if any of the following situations occurs:
403 * <li>The first argument is {@code null} or is a string of
406 * <li>The radix is either smaller than
407 * {@link java.lang.Character#MIN_RADIX} or
408 * larger than {@link java.lang.Character#MAX_RADIX}.
410 * <li>Any character of the string is not a digit of the specified
411 * radix, except that the first character may be a minus sign
412 * {@code '-'} (<code>'\u002D'</code>) or plus sign
413 * {@code '+'} (<code>'\u002B'</code>) provided that the
414 * string is longer than length 1.
416 * <li>The value represented by the string is not a value of type
422 * parseInt("0", 10) returns 0
423 * parseInt("473", 10) returns 473
424 * parseInt("+42", 10) returns 42
425 * parseInt("-0", 10) returns 0
426 * parseInt("-FF", 16) returns -255
427 * parseInt("1100110", 2) returns 102
428 * parseInt("2147483647", 10) returns 2147483647
429 * parseInt("-2147483648", 10) returns -2147483648
430 * parseInt("2147483648", 10) throws a NumberFormatException
431 * parseInt("99", 8) throws a NumberFormatException
432 * parseInt("Kona", 10) throws a NumberFormatException
433 * parseInt("Kona", 27) returns 411787
434 * </pre></blockquote>
436 * @param s the {@code String} containing the integer
437 * representation to be parsed
438 * @param radix the radix to be used while parsing {@code s}.
439 * @return the integer represented by the string argument in the
441 * @exception NumberFormatException if the {@code String}
442 * does not contain a parsable {@code int}.
444 public static int parseInt(String s, int radix)
445 throws NumberFormatException
448 * WARNING: This method may be invoked early during VM initialization
449 * before IntegerCache is initialized. Care must be taken to not use
450 * the valueOf method.
454 throw new NumberFormatException("null");
457 if (radix < Character.MIN_RADIX) {
458 throw new NumberFormatException("radix " + radix +
459 " less than Character.MIN_RADIX");
462 if (radix > Character.MAX_RADIX) {
463 throw new NumberFormatException("radix " + radix +
464 " greater than Character.MAX_RADIX");
468 boolean negative = false;
469 int i = 0, len = s.length();
470 int limit = -Integer.MAX_VALUE;
475 char firstChar = s.charAt(0);
476 if (firstChar < '0') { // Possible leading "+" or "-"
477 if (firstChar == '-') {
479 limit = Integer.MIN_VALUE;
480 } else if (firstChar != '+')
481 throw NumberFormatException.forInputString(s);
483 if (len == 1) // Cannot have lone "+" or "-"
484 throw NumberFormatException.forInputString(s);
487 multmin = limit / radix;
489 // Accumulating negatively avoids surprises near MAX_VALUE
490 digit = Character.digit(s.charAt(i++),radix);
492 throw NumberFormatException.forInputString(s);
494 if (result < multmin) {
495 throw NumberFormatException.forInputString(s);
498 if (result < limit + digit) {
499 throw NumberFormatException.forInputString(s);
504 throw NumberFormatException.forInputString(s);
506 return negative ? result : -result;
510 * Parses the string argument as a signed decimal integer. The
511 * characters in the string must all be decimal digits, except
512 * that the first character may be an ASCII minus sign {@code '-'}
513 * (<code>'\u002D'</code>) to indicate a negative value or an
514 * ASCII plus sign {@code '+'} (<code>'\u002B'</code>) to
515 * indicate a positive value. The resulting integer value is
516 * returned, exactly as if the argument and the radix 10 were
517 * given as arguments to the {@link #parseInt(java.lang.String,
520 * @param s a {@code String} containing the {@code int}
521 * representation to be parsed
522 * @return the integer value represented by the argument in decimal.
523 * @exception NumberFormatException if the string does not contain a
526 public static int parseInt(String s) throws NumberFormatException {
527 return parseInt(s,10);
531 * Returns an {@code Integer} object holding the value
532 * extracted from the specified {@code String} when parsed
533 * with the radix given by the second argument. The first argument
534 * is interpreted as representing a signed integer in the radix
535 * specified by the second argument, exactly as if the arguments
536 * were given to the {@link #parseInt(java.lang.String, int)}
537 * method. The result is an {@code Integer} object that
538 * represents the integer value specified by the string.
540 * <p>In other words, this method returns an {@code Integer}
541 * object equal to the value of:
544 * {@code new Integer(Integer.parseInt(s, radix))}
547 * @param s the string to be parsed.
548 * @param radix the radix to be used in interpreting {@code s}
549 * @return an {@code Integer} object holding the value
550 * represented by the string argument in the specified
552 * @exception NumberFormatException if the {@code String}
553 * does not contain a parsable {@code int}.
555 public static Integer valueOf(String s, int radix) throws NumberFormatException {
556 return Integer.valueOf(parseInt(s,radix));
560 * Returns an {@code Integer} object holding the
561 * value of the specified {@code String}. The argument is
562 * interpreted as representing a signed decimal integer, exactly
563 * as if the argument were given to the {@link
564 * #parseInt(java.lang.String)} method. The result is an
565 * {@code Integer} object that represents the integer value
566 * specified by the string.
568 * <p>In other words, this method returns an {@code Integer}
569 * object equal to the value of:
572 * {@code new Integer(Integer.parseInt(s))}
575 * @param s the string to be parsed.
576 * @return an {@code Integer} object holding the value
577 * represented by the string argument.
578 * @exception NumberFormatException if the string cannot be parsed
581 public static Integer valueOf(String s) throws NumberFormatException {
582 return Integer.valueOf(parseInt(s, 10));
586 * Cache to support the object identity semantics of autoboxing for values between
587 * -128 and 127 (inclusive) as required by JLS.
589 * The cache is initialized on first usage. The size of the cache
590 * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
591 * During VM initialization, java.lang.Integer.IntegerCache.high property
592 * may be set and saved in the private system properties in the
596 private static class IntegerCache {
597 static final int low = -128;
598 static final int high;
599 static final Integer cache[];
602 // high value may be configured by property
604 String integerCacheHighPropValue =
605 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
606 if (integerCacheHighPropValue != null) {
607 int i = parseInt(integerCacheHighPropValue);
608 i = Math.max(i, 127);
609 // Maximum array size is Integer.MAX_VALUE
610 h = Math.min(i, Integer.MAX_VALUE - (-low));
614 cache = new Integer[(high - low) + 1];
616 for(int k = 0; k < cache.length; k++)
617 cache[k] = new Integer(j++);
620 private IntegerCache() {}
624 * Returns an {@code Integer} instance representing the specified
625 * {@code int} value. If a new {@code Integer} instance is not
626 * required, this method should generally be used in preference to
627 * the constructor {@link #Integer(int)}, as this method is likely
628 * to yield significantly better space and time performance by
629 * caching frequently requested values.
631 * This method will always cache values in the range -128 to 127,
632 * inclusive, and may cache other values outside of this range.
634 * @param i an {@code int} value.
635 * @return an {@code Integer} instance representing {@code i}.
638 public static Integer valueOf(int i) {
639 assert IntegerCache.high >= 127;
640 if (i >= IntegerCache.low && i <= IntegerCache.high)
641 return IntegerCache.cache[i + (-IntegerCache.low)];
642 return new Integer(i);
646 * The value of the {@code Integer}.
650 private final int value;
653 * Constructs a newly allocated {@code Integer} object that
654 * represents the specified {@code int} value.
656 * @param value the value to be represented by the
657 * {@code Integer} object.
659 public Integer(int value) {
664 * Constructs a newly allocated {@code Integer} object that
665 * represents the {@code int} value indicated by the
666 * {@code String} parameter. The string is converted to an
667 * {@code int} value in exactly the manner used by the
668 * {@code parseInt} method for radix 10.
670 * @param s the {@code String} to be converted to an
672 * @exception NumberFormatException if the {@code String} does not
673 * contain a parsable integer.
674 * @see java.lang.Integer#parseInt(java.lang.String, int)
676 public Integer(String s) throws NumberFormatException {
677 this.value = parseInt(s, 10);
681 * Returns the value of this {@code Integer} as a
684 public byte byteValue() {
689 * Returns the value of this {@code Integer} as a
692 public short shortValue() {
697 * Returns the value of this {@code Integer} as an
700 public int intValue() {
705 * Returns the value of this {@code Integer} as a
708 public long longValue() {
713 * Returns the value of this {@code Integer} as a
716 public float floatValue() {
721 * Returns the value of this {@code Integer} as a
724 public double doubleValue() {
725 return (double)value;
729 * Returns a {@code String} object representing this
730 * {@code Integer}'s value. The value is converted to signed
731 * decimal representation and returned as a string, exactly as if
732 * the integer value were given as an argument to the {@link
733 * java.lang.Integer#toString(int)} method.
735 * @return a string representation of the value of this object in
738 public String toString() {
739 return toString(value);
743 * Returns a hash code for this {@code Integer}.
745 * @return a hash code value for this object, equal to the
746 * primitive {@code int} value represented by this
747 * {@code Integer} object.
749 public int hashCode() {
754 * Compares this object to the specified object. The result is
755 * {@code true} if and only if the argument is not
756 * {@code null} and is an {@code Integer} object that
757 * contains the same {@code int} value as this object.
759 * @param obj the object to compare with.
760 * @return {@code true} if the objects are the same;
761 * {@code false} otherwise.
763 public boolean equals(Object obj) {
764 if (obj instanceof Integer) {
765 return value == ((Integer)obj).intValue();
771 * Determines the integer value of the system property with the
774 * <p>The first argument is treated as the name of a system property.
775 * System properties are accessible through the
776 * {@link java.lang.System#getProperty(java.lang.String)} method. The
777 * string value of this property is then interpreted as an integer
778 * value and an {@code Integer} object representing this value is
779 * returned. Details of possible numeric formats can be found with
780 * the definition of {@code getProperty}.
782 * <p>If there is no property with the specified name, if the specified name
783 * is empty or {@code null}, or if the property does not have
784 * the correct numeric format, then {@code null} is returned.
786 * <p>In other words, this method returns an {@code Integer}
787 * object equal to the value of:
790 * {@code getInteger(nm, null)}
793 * @param nm property name.
794 * @return the {@code Integer} value of the property.
795 * @see java.lang.System#getProperty(java.lang.String)
796 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
798 public static Integer getInteger(String nm) {
799 return getInteger(nm, null);
803 * Determines the integer value of the system property with the
806 * <p>The first argument is treated as the name of a system property.
807 * System properties are accessible through the {@link
808 * java.lang.System#getProperty(java.lang.String)} method. The
809 * string value of this property is then interpreted as an integer
810 * value and an {@code Integer} object representing this value is
811 * returned. Details of possible numeric formats can be found with
812 * the definition of {@code getProperty}.
814 * <p>The second argument is the default value. An {@code Integer} object
815 * that represents the value of the second argument is returned if there
816 * is no property of the specified name, if the property does not have
817 * the correct numeric format, or if the specified name is empty or
820 * <p>In other words, this method returns an {@code Integer} object
821 * equal to the value of:
824 * {@code getInteger(nm, new Integer(val))}
827 * but in practice it may be implemented in a manner such as:
830 * Integer result = getInteger(nm, null);
831 * return (result == null) ? new Integer(val) : result;
832 * </pre></blockquote>
834 * to avoid the unnecessary allocation of an {@code Integer}
835 * object when the default value is not needed.
837 * @param nm property name.
838 * @param val default value.
839 * @return the {@code Integer} value of the property.
840 * @see java.lang.System#getProperty(java.lang.String)
841 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
843 public static Integer getInteger(String nm, int val) {
844 Integer result = getInteger(nm, null);
845 return (result == null) ? Integer.valueOf(val) : result;
849 * Returns the integer value of the system property with the
850 * specified name. The first argument is treated as the name of a
851 * system property. System properties are accessible through the
852 * {@link java.lang.System#getProperty(java.lang.String)} method.
853 * The string value of this property is then interpreted as an
854 * integer value, as per the {@code Integer.decode} method,
855 * and an {@code Integer} object representing this value is
858 * <ul><li>If the property value begins with the two ASCII characters
859 * {@code 0x} or the ASCII character {@code #}, not
860 * followed by a minus sign, then the rest of it is parsed as a
861 * hexadecimal integer exactly as by the method
862 * {@link #valueOf(java.lang.String, int)} with radix 16.
863 * <li>If the property value begins with the ASCII character
864 * {@code 0} followed by another character, it is parsed as an
865 * octal integer exactly as by the method
866 * {@link #valueOf(java.lang.String, int)} with radix 8.
867 * <li>Otherwise, the property value is parsed as a decimal integer
868 * exactly as by the method {@link #valueOf(java.lang.String, int)}
872 * <p>The second argument is the default value. The default value is
873 * returned if there is no property of the specified name, if the
874 * property does not have the correct numeric format, or if the
875 * specified name is empty or {@code null}.
877 * @param nm property name.
878 * @param val default value.
879 * @return the {@code Integer} value of the property.
880 * @see java.lang.System#getProperty(java.lang.String)
881 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
882 * @see java.lang.Integer#decode
884 public static Integer getInteger(String nm, Integer val) {
887 v = System.getProperty(nm);
888 } catch (IllegalArgumentException e) {
889 } catch (NullPointerException e) {
893 return Integer.decode(v);
894 } catch (NumberFormatException e) {
901 * Decodes a {@code String} into an {@code Integer}.
902 * Accepts decimal, hexadecimal, and octal numbers given
903 * by the following grammar:
907 * <dt><i>DecodableString:</i>
908 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
909 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
910 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
911 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
912 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
920 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
921 * are as defined in section 3.10.1 of
922 * <cite>The Java™ Language Specification</cite>,
923 * except that underscores are not accepted between digits.
925 * <p>The sequence of characters following an optional
926 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
927 * "{@code #}", or leading zero) is parsed as by the {@code
928 * Integer.parseInt} method with the indicated radix (10, 16, or
929 * 8). This sequence of characters must represent a positive
930 * value or a {@link NumberFormatException} will be thrown. The
931 * result is negated if first character of the specified {@code
932 * String} is the minus sign. No whitespace characters are
933 * permitted in the {@code String}.
935 * @param nm the {@code String} to decode.
936 * @return an {@code Integer} object holding the {@code int}
937 * value represented by {@code nm}
938 * @exception NumberFormatException if the {@code String} does not
939 * contain a parsable integer.
940 * @see java.lang.Integer#parseInt(java.lang.String, int)
942 public static Integer decode(String nm) throws NumberFormatException {
945 boolean negative = false;
948 if (nm.length() == 0)
949 throw new NumberFormatException("Zero length string");
950 char firstChar = nm.charAt(0);
951 // Handle sign, if present
952 if (firstChar == '-') {
955 } else if (firstChar == '+')
958 // Handle radix specifier, if present
959 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
963 else if (nm.startsWith("#", index)) {
967 else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
972 if (nm.startsWith("-", index) || nm.startsWith("+", index))
973 throw new NumberFormatException("Sign character in wrong position");
976 result = Integer.valueOf(nm.substring(index), radix);
977 result = negative ? Integer.valueOf(-result.intValue()) : result;
978 } catch (NumberFormatException e) {
979 // If number is Integer.MIN_VALUE, we'll end up here. The next line
980 // handles this case, and causes any genuine format error to be
982 String constant = negative ? ("-" + nm.substring(index))
983 : nm.substring(index);
984 result = Integer.valueOf(constant, radix);
990 * Compares two {@code Integer} objects numerically.
992 * @param anotherInteger the {@code Integer} to be compared.
993 * @return the value {@code 0} if this {@code Integer} is
994 * equal to the argument {@code Integer}; a value less than
995 * {@code 0} if this {@code Integer} is numerically less
996 * than the argument {@code Integer}; and a value greater
997 * than {@code 0} if this {@code Integer} is numerically
998 * greater than the argument {@code Integer} (signed
1002 public int compareTo(Integer anotherInteger) {
1003 return compare(this.value, anotherInteger.value);
1007 * Compares two {@code int} values numerically.
1008 * The value returned is identical to what would be returned by:
1010 * Integer.valueOf(x).compareTo(Integer.valueOf(y))
1013 * @param x the first {@code int} to compare
1014 * @param y the second {@code int} to compare
1015 * @return the value {@code 0} if {@code x == y};
1016 * a value less than {@code 0} if {@code x < y}; and
1017 * a value greater than {@code 0} if {@code x > y}
1020 public static int compare(int x, int y) {
1021 return (x < y) ? -1 : ((x == y) ? 0 : 1);
1028 * The number of bits used to represent an {@code int} value in two's
1029 * complement binary form.
1033 public static final int SIZE = 32;
1036 * Returns an {@code int} value with at most a single one-bit, in the
1037 * position of the highest-order ("leftmost") one-bit in the specified
1038 * {@code int} value. Returns zero if the specified value has no
1039 * one-bits in its two's complement binary representation, that is, if it
1042 * @return an {@code int} value with a single one-bit, in the position
1043 * of the highest-order one-bit in the specified value, or zero if
1044 * the specified value is itself equal to zero.
1047 public static int highestOneBit(int i) {
1054 return i - (i >>> 1);
1058 * Returns an {@code int} value with at most a single one-bit, in the
1059 * position of the lowest-order ("rightmost") one-bit in the specified
1060 * {@code int} value. Returns zero if the specified value has no
1061 * one-bits in its two's complement binary representation, that is, if it
1064 * @return an {@code int} value with a single one-bit, in the position
1065 * of the lowest-order one-bit in the specified value, or zero if
1066 * the specified value is itself equal to zero.
1069 public static int lowestOneBit(int i) {
1075 * Returns the number of zero bits preceding the highest-order
1076 * ("leftmost") one-bit in the two's complement binary representation
1077 * of the specified {@code int} value. Returns 32 if the
1078 * specified value has no one-bits in its two's complement representation,
1079 * in other words if it is equal to zero.
1081 * <p>Note that this method is closely related to the logarithm base 2.
1082 * For all positive {@code int} values x:
1084 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1085 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1088 * @return the number of zero bits preceding the highest-order
1089 * ("leftmost") one-bit in the two's complement binary representation
1090 * of the specified {@code int} value, or 32 if the value
1094 public static int numberOfLeadingZeros(int i) {
1099 if (i >>> 16 == 0) { n += 16; i <<= 16; }
1100 if (i >>> 24 == 0) { n += 8; i <<= 8; }
1101 if (i >>> 28 == 0) { n += 4; i <<= 4; }
1102 if (i >>> 30 == 0) { n += 2; i <<= 2; }
1108 * Returns the number of zero bits following the lowest-order ("rightmost")
1109 * one-bit in the two's complement binary representation of the specified
1110 * {@code int} value. Returns 32 if the specified value has no
1111 * one-bits in its two's complement representation, in other words if it is
1114 * @return the number of zero bits following the lowest-order ("rightmost")
1115 * one-bit in the two's complement binary representation of the
1116 * specified {@code int} value, or 32 if the value is equal
1120 public static int numberOfTrailingZeros(int i) {
1123 if (i == 0) return 32;
1125 y = i <<16; if (y != 0) { n = n -16; i = y; }
1126 y = i << 8; if (y != 0) { n = n - 8; i = y; }
1127 y = i << 4; if (y != 0) { n = n - 4; i = y; }
1128 y = i << 2; if (y != 0) { n = n - 2; i = y; }
1129 return n - ((i << 1) >>> 31);
1133 * Returns the number of one-bits in the two's complement binary
1134 * representation of the specified {@code int} value. This function is
1135 * sometimes referred to as the <i>population count</i>.
1137 * @return the number of one-bits in the two's complement binary
1138 * representation of the specified {@code int} value.
1141 public static int bitCount(int i) {
1143 i = i - ((i >>> 1) & 0x55555555);
1144 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1145 i = (i + (i >>> 4)) & 0x0f0f0f0f;
1152 * Returns the value obtained by rotating the two's complement binary
1153 * representation of the specified {@code int} value left by the
1154 * specified number of bits. (Bits shifted out of the left hand, or
1155 * high-order, side reenter on the right, or low-order.)
1157 * <p>Note that left rotation with a negative distance is equivalent to
1158 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1159 * distance)}. Note also that rotation by any multiple of 32 is a
1160 * no-op, so all but the last five bits of the rotation distance can be
1161 * ignored, even if the distance is negative: {@code rotateLeft(val,
1162 * distance) == rotateLeft(val, distance & 0x1F)}.
1164 * @return the value obtained by rotating the two's complement binary
1165 * representation of the specified {@code int} value left by the
1166 * specified number of bits.
1169 public static int rotateLeft(int i, int distance) {
1170 return (i << distance) | (i >>> -distance);
1174 * Returns the value obtained by rotating the two's complement binary
1175 * representation of the specified {@code int} value right by the
1176 * specified number of bits. (Bits shifted out of the right hand, or
1177 * low-order, side reenter on the left, or high-order.)
1179 * <p>Note that right rotation with a negative distance is equivalent to
1180 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1181 * distance)}. Note also that rotation by any multiple of 32 is a
1182 * no-op, so all but the last five bits of the rotation distance can be
1183 * ignored, even if the distance is negative: {@code rotateRight(val,
1184 * distance) == rotateRight(val, distance & 0x1F)}.
1186 * @return the value obtained by rotating the two's complement binary
1187 * representation of the specified {@code int} value right by the
1188 * specified number of bits.
1191 public static int rotateRight(int i, int distance) {
1192 return (i >>> distance) | (i << -distance);
1196 * Returns the value obtained by reversing the order of the bits in the
1197 * two's complement binary representation of the specified {@code int}
1200 * @return the value obtained by reversing order of the bits in the
1201 * specified {@code int} value.
1204 public static int reverse(int i) {
1206 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1207 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1208 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1209 i = (i << 24) | ((i & 0xff00) << 8) |
1210 ((i >>> 8) & 0xff00) | (i >>> 24);
1215 * Returns the signum function of the specified {@code int} value. (The
1216 * return value is -1 if the specified value is negative; 0 if the
1217 * specified value is zero; and 1 if the specified value is positive.)
1219 * @return the signum function of the specified {@code int} value.
1222 public static int signum(int i) {
1224 return (i >> 31) | (-i >>> 31);
1228 * Returns the value obtained by reversing the order of the bytes in the
1229 * two's complement representation of the specified {@code int} value.
1231 * @return the value obtained by reversing the bytes in the specified
1232 * {@code int} value.
1235 public static int reverseBytes(int i) {
1236 return ((i >>> 24) ) |
1237 ((i >> 8) & 0xFF00) |
1238 ((i << 8) & 0xFF0000) |
1242 /** use serialVersionUID from JDK 1.0.2 for interoperability */
1243 private static final long serialVersionUID = 1360826667806852920L;