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
29 * The {@code Integer} class wraps a value of the primitive type
30 * {@code int} in an object. An object of type {@code Integer}
31 * contains a single field whose type is {@code int}.
33 * <p>In addition, this class provides several methods for converting
34 * an {@code int} to a {@code String} and a {@code String} to an
35 * {@code int}, as well as other constants and methods useful when
36 * dealing with an {@code int}.
38 * <p>Implementation note: The implementations of the "bit twiddling"
39 * methods (such as {@link #highestOneBit(int) highestOneBit} and
40 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
41 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
42 * Delight</i>, (Addison Wesley, 2002).
45 * @author Arthur van Hoff
47 * @author Joseph D. Darcy
50 public final class Integer extends Number implements Comparable<Integer> {
52 * A constant holding the minimum value an {@code int} can
53 * have, -2<sup>31</sup>.
55 public static final int MIN_VALUE = 0x80000000;
58 * A constant holding the maximum value an {@code int} can
59 * have, 2<sup>31</sup>-1.
61 public static final int MAX_VALUE = 0x7fffffff;
64 * The {@code Class} instance representing the primitive type
69 public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
72 * All possible chars for representing a number as a String
74 final static char[] digits = {
75 '0' , '1' , '2' , '3' , '4' , '5' ,
76 '6' , '7' , '8' , '9' , 'a' , 'b' ,
77 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
78 'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
79 'o' , 'p' , 'q' , 'r' , 's' , 't' ,
80 'u' , 'v' , 'w' , 'x' , 'y' , 'z'
84 * Returns a string representation of the first argument in the
85 * radix specified by the second argument.
87 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
88 * or larger than {@code Character.MAX_RADIX}, then the radix
89 * {@code 10} is used instead.
91 * <p>If the first argument is negative, the first element of the
92 * result is the ASCII minus character {@code '-'}
93 * (<code>'\u002D'</code>). If the first argument is not
94 * negative, no sign character appears in the result.
96 * <p>The remaining characters of the result represent the magnitude
97 * of the first argument. If the magnitude is zero, it is
98 * represented by a single zero character {@code '0'}
99 * (<code>'\u0030'</code>); otherwise, the first character of
100 * the representation of the magnitude will not be the zero
101 * character. The following ASCII characters are used as digits:
104 * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
107 * These are <code>'\u0030'</code> through
108 * <code>'\u0039'</code> and <code>'\u0061'</code> through
109 * <code>'\u007A'</code>. If {@code radix} is
110 * <var>N</var>, then the first <var>N</var> of these characters
111 * are used as radix-<var>N</var> digits in the order shown. Thus,
112 * the digits for hexadecimal (radix 16) are
113 * {@code 0123456789abcdef}. If uppercase letters are
114 * desired, the {@link java.lang.String#toUpperCase()} method may
115 * be called on the result:
118 * {@code Integer.toString(n, 16).toUpperCase()}
121 * @param i an integer to be converted to a string.
122 * @param radix the radix to use in the string representation.
123 * @return a string representation of the argument in the specified radix.
124 * @see java.lang.Character#MAX_RADIX
125 * @see java.lang.Character#MIN_RADIX
127 public static String toString(int i, int radix) {
129 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
132 /* Use the faster version */
137 char buf[] = new char[33];
138 boolean negative = (i < 0);
145 while (i <= -radix) {
146 buf[charPos--] = digits[-(i % radix)];
149 buf[charPos] = digits[-i];
152 buf[--charPos] = '-';
155 return new String(buf, charPos, (33 - charPos));
159 * Returns a string representation of the integer argument as an
160 * unsigned integer in base 16.
162 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
163 * if the argument is negative; otherwise, it is equal to the
164 * argument. This value is converted to a string of ASCII digits
165 * in hexadecimal (base 16) with no extra leading
166 * {@code 0}s. If the unsigned magnitude is zero, it is
167 * represented by a single zero character {@code '0'}
168 * (<code>'\u0030'</code>); otherwise, the first character of
169 * the representation of the unsigned magnitude will not be the
170 * zero character. The following characters are used as
171 * hexadecimal digits:
174 * {@code 0123456789abcdef}
177 * These are the characters <code>'\u0030'</code> through
178 * <code>'\u0039'</code> and <code>'\u0061'</code> through
179 * <code>'\u0066'</code>. If uppercase letters are
180 * desired, the {@link java.lang.String#toUpperCase()} method may
181 * be called on the result:
184 * {@code Integer.toHexString(n).toUpperCase()}
187 * @param i an integer to be converted to a string.
188 * @return the string representation of the unsigned integer value
189 * represented by the argument in hexadecimal (base 16).
192 public static String toHexString(int i) {
193 return toUnsignedString(i, 4);
197 * Returns a string representation of the integer argument as an
198 * unsigned integer in base 8.
200 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
201 * if the argument is negative; otherwise, it is equal to the
202 * argument. This value is converted to a string of ASCII digits
203 * in octal (base 8) with no extra leading {@code 0}s.
205 * <p>If the unsigned magnitude is zero, it is represented by a
206 * single zero character {@code '0'}
207 * (<code>'\u0030'</code>); otherwise, the first character of
208 * the representation of the unsigned magnitude will not be the
209 * zero character. The following characters are used as octal
216 * These are the characters <code>'\u0030'</code> through
217 * <code>'\u0037'</code>.
219 * @param i an integer to be converted to a string.
220 * @return the string representation of the unsigned integer value
221 * represented by the argument in octal (base 8).
224 public static String toOctalString(int i) {
225 return toUnsignedString(i, 3);
229 * Returns a string representation of the integer argument as an
230 * unsigned integer in base 2.
232 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
233 * if the argument is negative; otherwise it is equal to the
234 * argument. This value is converted to a string of ASCII digits
235 * in binary (base 2) with no extra leading {@code 0}s.
236 * If the unsigned magnitude is zero, it is represented by a
237 * single zero character {@code '0'}
238 * (<code>'\u0030'</code>); otherwise, the first character of
239 * the representation of the unsigned magnitude will not be the
240 * zero character. The characters {@code '0'}
241 * (<code>'\u0030'</code>) and {@code '1'}
242 * (<code>'\u0031'</code>) are used as binary digits.
244 * @param i an integer to be converted to a string.
245 * @return the string representation of the unsigned integer value
246 * represented by the argument in binary (base 2).
249 public static String toBinaryString(int i) {
250 return toUnsignedString(i, 1);
254 * Convert the integer to an unsigned number.
256 private static String toUnsignedString(int i, int shift) {
257 char[] buf = new char[32];
259 int radix = 1 << shift;
260 int mask = radix - 1;
262 buf[--charPos] = digits[i & mask];
266 return new String(buf, charPos, (32 - charPos));
270 final static char [] DigitTens = {
271 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
272 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
273 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
274 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
275 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
276 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
277 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
278 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
279 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
280 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
283 final static char [] DigitOnes = {
284 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
285 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
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',
296 // I use the "invariant division by multiplication" trick to
297 // accelerate Integer.toString. In particular we want to
298 // avoid division by 10.
300 // The "trick" has roughly the same performance characteristics
301 // as the "classic" Integer.toString code on a non-JIT VM.
302 // The trick avoids .rem and .div calls but has a longer code
303 // path and is thus dominated by dispatch overhead. In the
304 // JIT case the dispatch overhead doesn't exist and the
305 // "trick" is considerably faster than the classic code.
307 // TODO-FIXME: convert (x * 52429) into the equiv shift-add
310 // RE: Division by Invariant Integers using Multiplication
311 // T Gralund, P Montgomery
316 * Returns a {@code String} object representing the
317 * specified integer. The argument is converted to signed decimal
318 * representation and returned as a string, exactly as if the
319 * argument and radix 10 were given as arguments to the {@link
320 * #toString(int, int)} method.
322 * @param i an integer to be converted.
323 * @return a string representation of the argument in base 10.
325 public static String toString(int i) {
326 if (i == Integer.MIN_VALUE)
327 return "-2147483648";
328 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
329 char[] buf = new char[size];
330 getChars(i, size, buf);
331 return new String(0, size, buf);
335 * Places characters representing the integer i into the
336 * character array buf. The characters are placed into
337 * the buffer backwards starting with the least significant
338 * digit at the specified index (exclusive), and working
339 * backwards from there.
341 * Will fail if i == Integer.MIN_VALUE
343 static void getChars(int i, int index, char[] buf) {
353 // Generate two digits per iteration
356 // really: r = i - (q * 100);
357 r = i - ((q << 6) + (q << 5) + (q << 2));
359 buf [--charPos] = DigitOnes[r];
360 buf [--charPos] = DigitTens[r];
363 // Fall thru to fast mode for smaller numbers
364 // assert(i <= 65536, i);
366 q = (i * 52429) >>> (16+3);
367 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
368 buf [--charPos] = digits [r];
373 buf [--charPos] = sign;
377 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
378 99999999, 999999999, Integer.MAX_VALUE };
380 // Requires positive x
381 static int stringSize(int x) {
383 if (x <= sizeTable[i])
388 * Parses the string argument as a signed integer in the radix
389 * specified by the second argument. The characters in the string
390 * must all be digits of the specified radix (as determined by
391 * whether {@link java.lang.Character#digit(char, int)} returns a
392 * nonnegative value), except that the first character may be an
393 * ASCII minus sign {@code '-'} (<code>'\u002D'</code>) to
394 * indicate a negative value or an ASCII plus sign {@code '+'}
395 * (<code>'\u002B'</code>) to indicate a positive value. The
396 * resulting integer value is returned.
398 * <p>An exception of type {@code NumberFormatException} is
399 * thrown if any of the following situations occurs:
401 * <li>The first argument is {@code null} or is a string of
404 * <li>The radix is either smaller than
405 * {@link java.lang.Character#MIN_RADIX} or
406 * larger than {@link java.lang.Character#MAX_RADIX}.
408 * <li>Any character of the string is not a digit of the specified
409 * radix, except that the first character may be a minus sign
410 * {@code '-'} (<code>'\u002D'</code>) or plus sign
411 * {@code '+'} (<code>'\u002B'</code>) provided that the
412 * string is longer than length 1.
414 * <li>The value represented by the string is not a value of type
420 * parseInt("0", 10) returns 0
421 * parseInt("473", 10) returns 473
422 * parseInt("+42", 10) returns 42
423 * parseInt("-0", 10) returns 0
424 * parseInt("-FF", 16) returns -255
425 * parseInt("1100110", 2) returns 102
426 * parseInt("2147483647", 10) returns 2147483647
427 * parseInt("-2147483648", 10) returns -2147483648
428 * parseInt("2147483648", 10) throws a NumberFormatException
429 * parseInt("99", 8) throws a NumberFormatException
430 * parseInt("Kona", 10) throws a NumberFormatException
431 * parseInt("Kona", 27) returns 411787
432 * </pre></blockquote>
434 * @param s the {@code String} containing the integer
435 * representation to be parsed
436 * @param radix the radix to be used while parsing {@code s}.
437 * @return the integer represented by the string argument in the
439 * @exception NumberFormatException if the {@code String}
440 * does not contain a parsable {@code int}.
442 public static int parseInt(String s, int radix)
443 throws NumberFormatException
446 * WARNING: This method may be invoked early during VM initialization
447 * before IntegerCache is initialized. Care must be taken to not use
448 * the valueOf method.
452 throw new NumberFormatException("null");
455 if (radix < Character.MIN_RADIX) {
456 throw new NumberFormatException("radix " + radix +
457 " less than Character.MIN_RADIX");
460 if (radix > Character.MAX_RADIX) {
461 throw new NumberFormatException("radix " + radix +
462 " greater than Character.MAX_RADIX");
466 boolean negative = false;
467 int i = 0, len = s.length();
468 int limit = -Integer.MAX_VALUE;
473 char firstChar = s.charAt(0);
474 if (firstChar < '0') { // Possible leading "+" or "-"
475 if (firstChar == '-') {
477 limit = Integer.MIN_VALUE;
478 } else if (firstChar != '+')
479 throw NumberFormatException.forInputString(s);
481 if (len == 1) // Cannot have lone "+" or "-"
482 throw NumberFormatException.forInputString(s);
485 multmin = limit / radix;
487 // Accumulating negatively avoids surprises near MAX_VALUE
488 digit = Character.digit(s.charAt(i++),radix);
490 throw NumberFormatException.forInputString(s);
492 if (result < multmin) {
493 throw NumberFormatException.forInputString(s);
496 if (result < limit + digit) {
497 throw NumberFormatException.forInputString(s);
502 throw NumberFormatException.forInputString(s);
504 return negative ? result : -result;
508 * Parses the string argument as a signed decimal integer. The
509 * characters in the string must all be decimal digits, except
510 * that the first character may be an ASCII minus sign {@code '-'}
511 * (<code>'\u002D'</code>) to indicate a negative value or an
512 * ASCII plus sign {@code '+'} (<code>'\u002B'</code>) to
513 * indicate a positive value. The resulting integer value is
514 * returned, exactly as if the argument and the radix 10 were
515 * given as arguments to the {@link #parseInt(java.lang.String,
518 * @param s a {@code String} containing the {@code int}
519 * representation to be parsed
520 * @return the integer value represented by the argument in decimal.
521 * @exception NumberFormatException if the string does not contain a
524 public static int parseInt(String s) throws NumberFormatException {
525 return parseInt(s,10);
529 * Returns an {@code Integer} object holding the value
530 * extracted from the specified {@code String} when parsed
531 * with the radix given by the second argument. The first argument
532 * is interpreted as representing a signed integer in the radix
533 * specified by the second argument, exactly as if the arguments
534 * were given to the {@link #parseInt(java.lang.String, int)}
535 * method. The result is an {@code Integer} object that
536 * represents the integer value specified by the string.
538 * <p>In other words, this method returns an {@code Integer}
539 * object equal to the value of:
542 * {@code new Integer(Integer.parseInt(s, radix))}
545 * @param s the string to be parsed.
546 * @param radix the radix to be used in interpreting {@code s}
547 * @return an {@code Integer} object holding the value
548 * represented by the string argument in the specified
550 * @exception NumberFormatException if the {@code String}
551 * does not contain a parsable {@code int}.
553 public static Integer valueOf(String s, int radix) throws NumberFormatException {
554 return Integer.valueOf(parseInt(s,radix));
558 * Returns an {@code Integer} object holding the
559 * value of the specified {@code String}. The argument is
560 * interpreted as representing a signed decimal integer, exactly
561 * as if the argument were given to the {@link
562 * #parseInt(java.lang.String)} method. The result is an
563 * {@code Integer} object that represents the integer value
564 * specified by the string.
566 * <p>In other words, this method returns an {@code Integer}
567 * object equal to the value of:
570 * {@code new Integer(Integer.parseInt(s))}
573 * @param s the string to be parsed.
574 * @return an {@code Integer} object holding the value
575 * represented by the string argument.
576 * @exception NumberFormatException if the string cannot be parsed
579 public static Integer valueOf(String s) throws NumberFormatException {
580 return Integer.valueOf(parseInt(s, 10));
584 * Cache to support the object identity semantics of autoboxing for values between
585 * -128 and 127 (inclusive) as required by JLS.
587 * The cache is initialized on first usage. The size of the cache
588 * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
589 * During VM initialization, java.lang.Integer.IntegerCache.high property
590 * may be set and saved in the private system properties in the
594 private static class IntegerCache {
595 static final int low = -128;
596 static final int high;
597 static final Integer cache[];
600 // high value may be configured by property
602 String integerCacheHighPropValue =
603 AbstractStringBuilder.getProperty("java.lang.Integer.IntegerCache.high");
604 if (integerCacheHighPropValue != null) {
605 int i = parseInt(integerCacheHighPropValue);
606 i = Math.max(i, 127);
607 // Maximum array size is Integer.MAX_VALUE
608 h = Math.min(i, Integer.MAX_VALUE - (-low));
612 cache = new Integer[(high - low) + 1];
614 for(int k = 0; k < cache.length; k++)
615 cache[k] = new Integer(j++);
618 private IntegerCache() {}
622 * Returns an {@code Integer} instance representing the specified
623 * {@code int} value. If a new {@code Integer} instance is not
624 * required, this method should generally be used in preference to
625 * the constructor {@link #Integer(int)}, as this method is likely
626 * to yield significantly better space and time performance by
627 * caching frequently requested values.
629 * This method will always cache values in the range -128 to 127,
630 * inclusive, and may cache other values outside of this range.
632 * @param i an {@code int} value.
633 * @return an {@code Integer} instance representing {@code i}.
636 public static Integer valueOf(int i) {
637 //assert IntegerCache.high >= 127;
638 if (i >= IntegerCache.low && i <= IntegerCache.high)
639 return IntegerCache.cache[i + (-IntegerCache.low)];
640 return new Integer(i);
644 * The value of the {@code Integer}.
648 private final int value;
651 * Constructs a newly allocated {@code Integer} object that
652 * represents the specified {@code int} value.
654 * @param value the value to be represented by the
655 * {@code Integer} object.
657 public Integer(int value) {
662 * Constructs a newly allocated {@code Integer} object that
663 * represents the {@code int} value indicated by the
664 * {@code String} parameter. The string is converted to an
665 * {@code int} value in exactly the manner used by the
666 * {@code parseInt} method for radix 10.
668 * @param s the {@code String} to be converted to an
670 * @exception NumberFormatException if the {@code String} does not
671 * contain a parsable integer.
672 * @see java.lang.Integer#parseInt(java.lang.String, int)
674 public Integer(String s) throws NumberFormatException {
675 this.value = parseInt(s, 10);
679 * Returns the value of this {@code Integer} as a
682 public byte byteValue() {
687 * Returns the value of this {@code Integer} as a
690 public short shortValue() {
695 * Returns the value of this {@code Integer} as an
698 public int intValue() {
703 * Returns the value of this {@code Integer} as a
706 public long longValue() {
711 * Returns the value of this {@code Integer} as a
714 public float floatValue() {
719 * Returns the value of this {@code Integer} as a
722 public double doubleValue() {
723 return (double)value;
727 * Returns a {@code String} object representing this
728 * {@code Integer}'s value. The value is converted to signed
729 * decimal representation and returned as a string, exactly as if
730 * the integer value were given as an argument to the {@link
731 * java.lang.Integer#toString(int)} method.
733 * @return a string representation of the value of this object in
736 public String toString() {
737 return toString(value);
741 * Returns a hash code for this {@code Integer}.
743 * @return a hash code value for this object, equal to the
744 * primitive {@code int} value represented by this
745 * {@code Integer} object.
747 public int hashCode() {
752 * Compares this object to the specified object. The result is
753 * {@code true} if and only if the argument is not
754 * {@code null} and is an {@code Integer} object that
755 * contains the same {@code int} value as this object.
757 * @param obj the object to compare with.
758 * @return {@code true} if the objects are the same;
759 * {@code false} otherwise.
761 public boolean equals(Object obj) {
762 if (obj instanceof Integer) {
763 return value == ((Integer)obj).intValue();
769 * Determines the integer value of the system property with the
772 * <p>The first argument is treated as the name of a system property.
773 * System properties are accessible through the
774 * {@link java.lang.System#getProperty(java.lang.String)} method. The
775 * string value of this property is then interpreted as an integer
776 * value and an {@code Integer} object representing this value is
777 * returned. Details of possible numeric formats can be found with
778 * the definition of {@code getProperty}.
780 * <p>If there is no property with the specified name, if the specified name
781 * is empty or {@code null}, or if the property does not have
782 * the correct numeric format, then {@code null} is returned.
784 * <p>In other words, this method returns an {@code Integer}
785 * object equal to the value of:
788 * {@code getInteger(nm, null)}
791 * @param nm property name.
792 * @return the {@code Integer} value of the property.
793 * @see java.lang.System#getProperty(java.lang.String)
794 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
796 public static Integer getInteger(String nm) {
797 return getInteger(nm, null);
801 * Determines the integer value of the system property with the
804 * <p>The first argument is treated as the name of a system property.
805 * System properties are accessible through the {@link
806 * java.lang.System#getProperty(java.lang.String)} method. The
807 * string value of this property is then interpreted as an integer
808 * value and an {@code Integer} object representing this value is
809 * returned. Details of possible numeric formats can be found with
810 * the definition of {@code getProperty}.
812 * <p>The second argument is the default value. An {@code Integer} object
813 * that represents the value of the second argument is returned if there
814 * is no property of the specified name, if the property does not have
815 * the correct numeric format, or if the specified name is empty or
818 * <p>In other words, this method returns an {@code Integer} object
819 * equal to the value of:
822 * {@code getInteger(nm, new Integer(val))}
825 * but in practice it may be implemented in a manner such as:
828 * Integer result = getInteger(nm, null);
829 * return (result == null) ? new Integer(val) : result;
830 * </pre></blockquote>
832 * to avoid the unnecessary allocation of an {@code Integer}
833 * object when the default value is not needed.
835 * @param nm property name.
836 * @param val default value.
837 * @return the {@code Integer} value of the property.
838 * @see java.lang.System#getProperty(java.lang.String)
839 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
841 public static Integer getInteger(String nm, int val) {
842 Integer result = getInteger(nm, null);
843 return (result == null) ? Integer.valueOf(val) : result;
847 * Returns the integer value of the system property with the
848 * specified name. The first argument is treated as the name of a
849 * system property. System properties are accessible through the
850 * {@link java.lang.System#getProperty(java.lang.String)} method.
851 * The string value of this property is then interpreted as an
852 * integer value, as per the {@code Integer.decode} method,
853 * and an {@code Integer} object representing this value is
856 * <ul><li>If the property value begins with the two ASCII characters
857 * {@code 0x} or the ASCII character {@code #}, not
858 * followed by a minus sign, then the rest of it is parsed as a
859 * hexadecimal integer exactly as by the method
860 * {@link #valueOf(java.lang.String, int)} with radix 16.
861 * <li>If the property value begins with the ASCII character
862 * {@code 0} followed by another character, it is parsed as an
863 * octal integer exactly as by the method
864 * {@link #valueOf(java.lang.String, int)} with radix 8.
865 * <li>Otherwise, the property value is parsed as a decimal integer
866 * exactly as by the method {@link #valueOf(java.lang.String, int)}
870 * <p>The second argument is the default value. The default value is
871 * returned if there is no property of the specified name, if the
872 * property does not have the correct numeric format, or if the
873 * specified name is empty or {@code null}.
875 * @param nm property name.
876 * @param val default value.
877 * @return the {@code Integer} value of the property.
878 * @see java.lang.System#getProperty(java.lang.String)
879 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
880 * @see java.lang.Integer#decode
882 public static Integer getInteger(String nm, Integer val) {
885 v = AbstractStringBuilder.getProperty(nm);
886 } catch (IllegalArgumentException e) {
887 } catch (NullPointerException e) {
891 return Integer.decode(v);
892 } catch (NumberFormatException e) {
899 * Decodes a {@code String} into an {@code Integer}.
900 * Accepts decimal, hexadecimal, and octal numbers given
901 * by the following grammar:
905 * <dt><i>DecodableString:</i>
906 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
907 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
908 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
909 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
910 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
918 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
919 * are as defined in section 3.10.1 of
920 * <cite>The Java™ Language Specification</cite>,
921 * except that underscores are not accepted between digits.
923 * <p>The sequence of characters following an optional
924 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
925 * "{@code #}", or leading zero) is parsed as by the {@code
926 * Integer.parseInt} method with the indicated radix (10, 16, or
927 * 8). This sequence of characters must represent a positive
928 * value or a {@link NumberFormatException} will be thrown. The
929 * result is negated if first character of the specified {@code
930 * String} is the minus sign. No whitespace characters are
931 * permitted in the {@code String}.
933 * @param nm the {@code String} to decode.
934 * @return an {@code Integer} object holding the {@code int}
935 * value represented by {@code nm}
936 * @exception NumberFormatException if the {@code String} does not
937 * contain a parsable integer.
938 * @see java.lang.Integer#parseInt(java.lang.String, int)
940 public static Integer decode(String nm) throws NumberFormatException {
943 boolean negative = false;
946 if (nm.length() == 0)
947 throw new NumberFormatException("Zero length string");
948 char firstChar = nm.charAt(0);
949 // Handle sign, if present
950 if (firstChar == '-') {
953 } else if (firstChar == '+')
956 // Handle radix specifier, if present
957 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
961 else if (nm.startsWith("#", index)) {
965 else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
970 if (nm.startsWith("-", index) || nm.startsWith("+", index))
971 throw new NumberFormatException("Sign character in wrong position");
974 result = Integer.valueOf(nm.substring(index), radix);
975 result = negative ? Integer.valueOf(-result.intValue()) : result;
976 } catch (NumberFormatException e) {
977 // If number is Integer.MIN_VALUE, we'll end up here. The next line
978 // handles this case, and causes any genuine format error to be
980 String constant = negative ? ("-" + nm.substring(index))
981 : nm.substring(index);
982 result = Integer.valueOf(constant, radix);
988 * Compares two {@code Integer} objects numerically.
990 * @param anotherInteger the {@code Integer} to be compared.
991 * @return the value {@code 0} if this {@code Integer} is
992 * equal to the argument {@code Integer}; a value less than
993 * {@code 0} if this {@code Integer} is numerically less
994 * than the argument {@code Integer}; and a value greater
995 * than {@code 0} if this {@code Integer} is numerically
996 * greater than the argument {@code Integer} (signed
1000 public int compareTo(Integer anotherInteger) {
1001 return compare(this.value, anotherInteger.value);
1005 * Compares two {@code int} values numerically.
1006 * The value returned is identical to what would be returned by:
1008 * Integer.valueOf(x).compareTo(Integer.valueOf(y))
1011 * @param x the first {@code int} to compare
1012 * @param y the second {@code int} to compare
1013 * @return the value {@code 0} if {@code x == y};
1014 * a value less than {@code 0} if {@code x < y}; and
1015 * a value greater than {@code 0} if {@code x > y}
1018 public static int compare(int x, int y) {
1019 return (x < y) ? -1 : ((x == y) ? 0 : 1);
1026 * The number of bits used to represent an {@code int} value in two's
1027 * complement binary form.
1031 public static final int SIZE = 32;
1034 * Returns an {@code int} value with at most a single one-bit, in the
1035 * position of the highest-order ("leftmost") one-bit in the specified
1036 * {@code int} value. Returns zero if the specified value has no
1037 * one-bits in its two's complement binary representation, that is, if it
1040 * @return an {@code int} value with a single one-bit, in the position
1041 * of the highest-order one-bit in the specified value, or zero if
1042 * the specified value is itself equal to zero.
1045 public static int highestOneBit(int i) {
1052 return i - (i >>> 1);
1056 * Returns an {@code int} value with at most a single one-bit, in the
1057 * position of the lowest-order ("rightmost") one-bit in the specified
1058 * {@code int} value. Returns zero if the specified value has no
1059 * one-bits in its two's complement binary representation, that is, if it
1062 * @return an {@code int} value with a single one-bit, in the position
1063 * of the lowest-order one-bit in the specified value, or zero if
1064 * the specified value is itself equal to zero.
1067 public static int lowestOneBit(int i) {
1073 * Returns the number of zero bits preceding the highest-order
1074 * ("leftmost") one-bit in the two's complement binary representation
1075 * of the specified {@code int} value. Returns 32 if the
1076 * specified value has no one-bits in its two's complement representation,
1077 * in other words if it is equal to zero.
1079 * <p>Note that this method is closely related to the logarithm base 2.
1080 * For all positive {@code int} values x:
1082 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1083 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1086 * @return the number of zero bits preceding the highest-order
1087 * ("leftmost") one-bit in the two's complement binary representation
1088 * of the specified {@code int} value, or 32 if the value
1092 public static int numberOfLeadingZeros(int i) {
1097 if (i >>> 16 == 0) { n += 16; i <<= 16; }
1098 if (i >>> 24 == 0) { n += 8; i <<= 8; }
1099 if (i >>> 28 == 0) { n += 4; i <<= 4; }
1100 if (i >>> 30 == 0) { n += 2; i <<= 2; }
1106 * Returns the number of zero bits following the lowest-order ("rightmost")
1107 * one-bit in the two's complement binary representation of the specified
1108 * {@code int} value. Returns 32 if the specified value has no
1109 * one-bits in its two's complement representation, in other words if it is
1112 * @return the number of zero bits following the lowest-order ("rightmost")
1113 * one-bit in the two's complement binary representation of the
1114 * specified {@code int} value, or 32 if the value is equal
1118 public static int numberOfTrailingZeros(int i) {
1121 if (i == 0) return 32;
1123 y = i <<16; if (y != 0) { n = n -16; i = y; }
1124 y = i << 8; if (y != 0) { n = n - 8; i = y; }
1125 y = i << 4; if (y != 0) { n = n - 4; i = y; }
1126 y = i << 2; if (y != 0) { n = n - 2; i = y; }
1127 return n - ((i << 1) >>> 31);
1131 * Returns the number of one-bits in the two's complement binary
1132 * representation of the specified {@code int} value. This function is
1133 * sometimes referred to as the <i>population count</i>.
1135 * @return the number of one-bits in the two's complement binary
1136 * representation of the specified {@code int} value.
1139 public static int bitCount(int i) {
1141 i = i - ((i >>> 1) & 0x55555555);
1142 i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1143 i = (i + (i >>> 4)) & 0x0f0f0f0f;
1150 * Returns the value obtained by rotating the two's complement binary
1151 * representation of the specified {@code int} value left by the
1152 * specified number of bits. (Bits shifted out of the left hand, or
1153 * high-order, side reenter on the right, or low-order.)
1155 * <p>Note that left rotation with a negative distance is equivalent to
1156 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1157 * distance)}. Note also that rotation by any multiple of 32 is a
1158 * no-op, so all but the last five bits of the rotation distance can be
1159 * ignored, even if the distance is negative: {@code rotateLeft(val,
1160 * distance) == rotateLeft(val, distance & 0x1F)}.
1162 * @return the value obtained by rotating the two's complement binary
1163 * representation of the specified {@code int} value left by the
1164 * specified number of bits.
1167 public static int rotateLeft(int i, int distance) {
1168 return (i << distance) | (i >>> -distance);
1172 * Returns the value obtained by rotating the two's complement binary
1173 * representation of the specified {@code int} value right by the
1174 * specified number of bits. (Bits shifted out of the right hand, or
1175 * low-order, side reenter on the left, or high-order.)
1177 * <p>Note that right rotation with a negative distance is equivalent to
1178 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1179 * distance)}. Note also that rotation by any multiple of 32 is a
1180 * no-op, so all but the last five bits of the rotation distance can be
1181 * ignored, even if the distance is negative: {@code rotateRight(val,
1182 * distance) == rotateRight(val, distance & 0x1F)}.
1184 * @return the value obtained by rotating the two's complement binary
1185 * representation of the specified {@code int} value right by the
1186 * specified number of bits.
1189 public static int rotateRight(int i, int distance) {
1190 return (i >>> distance) | (i << -distance);
1194 * Returns the value obtained by reversing the order of the bits in the
1195 * two's complement binary representation of the specified {@code int}
1198 * @return the value obtained by reversing order of the bits in the
1199 * specified {@code int} value.
1202 public static int reverse(int i) {
1204 i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1205 i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1206 i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1207 i = (i << 24) | ((i & 0xff00) << 8) |
1208 ((i >>> 8) & 0xff00) | (i >>> 24);
1213 * Returns the signum function of the specified {@code int} value. (The
1214 * return value is -1 if the specified value is negative; 0 if the
1215 * specified value is zero; and 1 if the specified value is positive.)
1217 * @return the signum function of the specified {@code int} value.
1220 public static int signum(int i) {
1222 return (i >> 31) | (-i >>> 31);
1226 * Returns the value obtained by reversing the order of the bytes in the
1227 * two's complement representation of the specified {@code int} value.
1229 * @return the value obtained by reversing the bytes in the specified
1230 * {@code int} value.
1233 public static int reverseBytes(int i) {
1234 return ((i >>> 24) ) |
1235 ((i >> 8) & 0xFF00) |
1236 ((i << 8) & 0xFF0000) |
1240 /** use serialVersionUID from JDK 1.0.2 for interoperability */
1241 private static final long serialVersionUID = 1360826667806852920L;