Remove old autovect-branch by moving to "dead" directory.
[official-gcc.git] / old-autovect-branch / libjava / classpath / java / lang / Integer.java
blobf3fe85f50412969c1be95429980e304aa72b0bed
1 /* Integer.java -- object wrapper for int
2 Copyright (C) 1998, 1999, 2001, 2002, 2004, 2005
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
40 package java.lang;
42 /**
43 * Instances of class <code>Integer</code> represent primitive
44 * <code>int</code> values.
46 * Additionally, this class provides various helper functions and variables
47 * related to ints.
49 * @author Paul Fisher
50 * @author John Keiser
51 * @author Warren Levy
52 * @author Eric Blake (ebb9@email.byu.edu)
53 * @author Tom Tromey (tromey@redhat.com)
54 * @since 1.0
55 * @status largely updated to 1.5
57 public final class Integer extends Number implements Comparable
59 /**
60 * Compatible with JDK 1.0.2+.
62 private static final long serialVersionUID = 1360826667806852920L;
64 /**
65 * The minimum value an <code>int</code> can represent is -2147483648 (or
66 * -2<sup>31</sup>).
68 public static final int MIN_VALUE = 0x80000000;
70 /**
71 * The maximum value an <code>int</code> can represent is 2147483647 (or
72 * 2<sup>31</sup> - 1).
74 public static final int MAX_VALUE = 0x7fffffff;
76 /**
77 * The primitive type <code>int</code> is represented by this
78 * <code>Class</code> object.
79 * @since 1.1
81 public static final Class TYPE = VMClassLoader.getPrimitiveClass('I');
83 /**
84 * The number of bits needed to represent an <code>int</code>.
85 * @since 1.5
87 public static final int SIZE = 32;
89 // This caches some Integer values, and is used by boxing
90 // conversions via valueOf(). We must cache at least -128..127;
91 // these constants control how much we actually cache.
92 private static final int MIN_CACHE = -128;
93 private static final int MAX_CACHE = 127;
94 private static Integer[] intCache = new Integer[MAX_CACHE - MIN_CACHE + 1];
96 /**
97 * The immutable value of this Integer.
99 * @serial the wrapped int
101 private final int value;
104 * Create an <code>Integer</code> object representing the value of the
105 * <code>int</code> argument.
107 * @param value the value to use
109 public Integer(int value)
111 this.value = value;
115 * Create an <code>Integer</code> object representing the value of the
116 * argument after conversion to an <code>int</code>.
118 * @param s the string to convert
119 * @throws NumberFormatException if the String does not contain an int
120 * @see #valueOf(String)
122 public Integer(String s)
124 value = parseInt(s, 10, false);
128 * Converts the <code>int</code> to a <code>String</code> using
129 * the specified radix (base). If the radix exceeds
130 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
131 * is used instead. If the result is negative, the leading character is
132 * '-' ('\\u002D'). The remaining characters come from
133 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
135 * @param num the <code>int</code> to convert to <code>String</code>
136 * @param radix the radix (base) to use in the conversion
137 * @return the <code>String</code> representation of the argument
139 public static String toString(int num, int radix)
141 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
142 radix = 10;
144 // For negative numbers, print out the absolute value w/ a leading '-'.
145 // Use an array large enough for a binary number.
146 char[] buffer = new char[33];
147 int i = 33;
148 boolean isNeg = false;
149 if (num < 0)
151 isNeg = true;
152 num = -num;
154 // When the value is MIN_VALUE, it overflows when made positive
155 if (num < 0)
157 buffer[--i] = digits[(int) (-(num + radix) % radix)];
158 num = -(num / radix);
164 buffer[--i] = digits[num % radix];
165 num /= radix;
167 while (num > 0);
169 if (isNeg)
170 buffer[--i] = '-';
172 // Package constructor avoids an array copy.
173 return new String(buffer, i, 33 - i, true);
177 * Converts the <code>int</code> to a <code>String</code> assuming it is
178 * unsigned in base 16.
180 * @param i the <code>int</code> to convert to <code>String</code>
181 * @return the <code>String</code> representation of the argument
183 public static String toHexString(int i)
185 return toUnsignedString(i, 4);
189 * Converts the <code>int</code> to a <code>String</code> assuming it is
190 * unsigned in base 8.
192 * @param i the <code>int</code> to convert to <code>String</code>
193 * @return the <code>String</code> representation of the argument
195 public static String toOctalString(int i)
197 return toUnsignedString(i, 3);
201 * Converts the <code>int</code> to a <code>String</code> assuming it is
202 * unsigned in base 2.
204 * @param i the <code>int</code> to convert to <code>String</code>
205 * @return the <code>String</code> representation of the argument
207 public static String toBinaryString(int i)
209 return toUnsignedString(i, 1);
213 * Converts the <code>int</code> to a <code>String</code> and assumes
214 * a radix of 10.
216 * @param i the <code>int</code> to convert to <code>String</code>
217 * @return the <code>String</code> representation of the argument
218 * @see #toString(int, int)
220 public static String toString(int i)
222 // This is tricky: in libgcj, String.valueOf(int) is a fast native
223 // implementation. In Classpath it just calls back to
224 // Integer.toString(int, int).
225 return String.valueOf(i);
229 * Converts the specified <code>String</code> into an <code>int</code>
230 * using the specified radix (base). The string must not be <code>null</code>
231 * or empty. It may begin with an optional '-', which will negate the answer,
232 * provided that there are also valid digits. Each digit is parsed as if by
233 * <code>Character.digit(d, radix)</code>, and must be in the range
234 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
235 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
236 * Unlike Double.parseDouble, you may not have a leading '+'.
238 * @param str the <code>String</code> to convert
239 * @param radix the radix (base) to use in the conversion
240 * @return the <code>String</code> argument converted to <code>int</code>
241 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
242 * <code>int</code>
244 public static int parseInt(String str, int radix)
246 return parseInt(str, radix, false);
250 * Converts the specified <code>String</code> into an <code>int</code>.
251 * This function assumes a radix of 10.
253 * @param s the <code>String</code> to convert
254 * @return the <code>int</code> value of <code>s</code>
255 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
256 * <code>int</code>
257 * @see #parseInt(String, int)
259 public static int parseInt(String s)
261 return parseInt(s, 10, false);
265 * Creates a new <code>Integer</code> object using the <code>String</code>
266 * and specified radix (base).
268 * @param s the <code>String</code> to convert
269 * @param radix the radix (base) to convert with
270 * @return the new <code>Integer</code>
271 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
272 * <code>int</code>
273 * @see #parseInt(String, int)
275 public static Integer valueOf(String s, int radix)
277 return new Integer(parseInt(s, radix, false));
281 * Creates a new <code>Integer</code> object using the <code>String</code>,
282 * assuming a radix of 10.
284 * @param s the <code>String</code> to convert
285 * @return the new <code>Integer</code>
286 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
287 * <code>int</code>
288 * @see #Integer(String)
289 * @see #parseInt(String)
291 public static Integer valueOf(String s)
293 return new Integer(parseInt(s, 10, false));
297 * Returns an <code>Integer</code> object wrapping the value.
298 * In contrast to the <code>Integer</code> constructor, this method
299 * will cache some values. It is used by boxing conversion.
301 * @param val the value to wrap
302 * @return the <code>Integer</code>
304 public static Integer valueOf(int val)
306 if (val < MIN_CACHE || val > MAX_CACHE)
307 return new Integer(val);
308 synchronized (intCache)
310 if (intCache[val - MIN_CACHE] == null)
311 intCache[val - MIN_CACHE] = new Integer(val);
312 return intCache[val - MIN_CACHE];
317 * Return the value of this <code>Integer</code> as a <code>byte</code>.
319 * @return the byte value
321 public byte byteValue()
323 return (byte) value;
327 * Return the value of this <code>Integer</code> as a <code>short</code>.
329 * @return the short value
331 public short shortValue()
333 return (short) value;
337 * Return the value of this <code>Integer</code>.
338 * @return the int value
340 public int intValue()
342 return value;
346 * Return the value of this <code>Integer</code> as a <code>long</code>.
348 * @return the long value
350 public long longValue()
352 return value;
356 * Return the value of this <code>Integer</code> as a <code>float</code>.
358 * @return the float value
360 public float floatValue()
362 return value;
366 * Return the value of this <code>Integer</code> as a <code>double</code>.
368 * @return the double value
370 public double doubleValue()
372 return value;
376 * Converts the <code>Integer</code> value to a <code>String</code> and
377 * assumes a radix of 10.
379 * @return the <code>String</code> representation
381 public String toString()
383 return String.valueOf(value);
387 * Return a hashcode representing this Object. <code>Integer</code>'s hash
388 * code is simply its value.
390 * @return this Object's hash code
392 public int hashCode()
394 return value;
398 * Returns <code>true</code> if <code>obj</code> is an instance of
399 * <code>Integer</code> and represents the same int value.
401 * @param obj the object to compare
402 * @return whether these Objects are semantically equal
404 public boolean equals(Object obj)
406 return obj instanceof Integer && value == ((Integer) obj).value;
410 * Get the specified system property as an <code>Integer</code>. The
411 * <code>decode()</code> method will be used to interpret the value of
412 * the property.
414 * @param nm the name of the system property
415 * @return the system property as an <code>Integer</code>, or null if the
416 * property is not found or cannot be decoded
417 * @throws SecurityException if accessing the system property is forbidden
418 * @see System#getProperty(String)
419 * @see #decode(String)
421 public static Integer getInteger(String nm)
423 return getInteger(nm, null);
427 * Get the specified system property as an <code>Integer</code>, or use a
428 * default <code>int</code> value if the property is not found or is not
429 * decodable. The <code>decode()</code> method will be used to interpret
430 * the value of the property.
432 * @param nm the name of the system property
433 * @param val the default value
434 * @return the value of the system property, or the default
435 * @throws SecurityException if accessing the system property is forbidden
436 * @see System#getProperty(String)
437 * @see #decode(String)
439 public static Integer getInteger(String nm, int val)
441 Integer result = getInteger(nm, null);
442 return result == null ? new Integer(val) : result;
446 * Get the specified system property as an <code>Integer</code>, or use a
447 * default <code>Integer</code> value if the property is not found or is
448 * not decodable. The <code>decode()</code> method will be used to
449 * interpret the value of the property.
451 * @param nm the name of the system property
452 * @param def the default value
453 * @return the value of the system property, or the default
454 * @throws SecurityException if accessing the system property is forbidden
455 * @see System#getProperty(String)
456 * @see #decode(String)
458 public static Integer getInteger(String nm, Integer def)
460 if (nm == null || "".equals(nm))
461 return def;
462 nm = System.getProperty(nm);
463 if (nm == null)
464 return def;
467 return decode(nm);
469 catch (NumberFormatException e)
471 return def;
476 * Convert the specified <code>String</code> into an <code>Integer</code>.
477 * The <code>String</code> may represent decimal, hexadecimal, or
478 * octal numbers.
480 * <p>The extended BNF grammar is as follows:<br>
481 * <pre>
482 * <em>DecodableString</em>:
483 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
484 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
485 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
486 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
487 * <em>DecimalNumber</em>:
488 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
489 * <em>DecimalDigit</em>:
490 * <em>Character.digit(d, 10) has value 0 to 9</em>
491 * <em>OctalDigit</em>:
492 * <em>Character.digit(d, 8) has value 0 to 7</em>
493 * <em>DecimalDigit</em>:
494 * <em>Character.digit(d, 16) has value 0 to 15</em>
495 * </pre>
496 * Finally, the value must be in the range <code>MIN_VALUE</code> to
497 * <code>MAX_VALUE</code>, or an exception is thrown.
499 * @param str the <code>String</code> to interpret
500 * @return the value of the String as an <code>Integer</code>
501 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
502 * <code>int</code>
503 * @throws NullPointerException if <code>s</code> is null
504 * @since 1.2
506 public static Integer decode(String str)
508 return new Integer(parseInt(str, 10, true));
512 * Compare two Integers numerically by comparing their <code>int</code>
513 * values. The result is positive if the first is greater, negative if the
514 * second is greater, and 0 if the two are equal.
516 * @param i the Integer to compare
517 * @return the comparison
518 * @since 1.2
520 public int compareTo(Integer i)
522 if (value == i.value)
523 return 0;
524 // Returns just -1 or 1 on inequality; doing math might overflow.
525 return value > i.value ? 1 : -1;
529 * Behaves like <code>compareTo(Integer)</code> unless the Object
530 * is not an <code>Integer</code>.
532 * @param o the object to compare
533 * @return the comparison
534 * @throws ClassCastException if the argument is not an <code>Integer</code>
535 * @see #compareTo(Integer)
536 * @see Comparable
537 * @since 1.2
539 public int compareTo(Object o)
541 return compareTo((Integer) o);
545 * Return the number of bits set in x.
546 * @param x value to examine
547 * @since 1.5
549 public static int bitCount(int x)
551 // Successively collapse alternating bit groups into a sum.
552 x = ((x >> 1) & 0x55555555) + (x & 0x55555555);
553 x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
554 x = ((x >> 4) & 0x0f0f0f0f) + (x & 0x0f0f0f0f);
555 x = ((x >> 8) & 0x00ff00ff) + (x & 0x00ff00ff);
556 return ((x >> 16) & 0x0000ffff) + (x & 0x0000ffff);
560 * Rotate x to the left by distance bits.
561 * @param x the value to rotate
562 * @param distance the number of bits by which to rotate
563 * @since 1.5
565 public static int rotateLeft(int x, int distance)
567 // This trick works because the shift operators implicitly mask
568 // the shift count.
569 return (x << distance) | (x >>> - distance);
573 * Rotate x to the right by distance bits.
574 * @param x the value to rotate
575 * @param distance the number of bits by which to rotate
576 * @since 1.5
578 public static int rotateRight(int x, int distance)
580 // This trick works because the shift operators implicitly mask
581 // the shift count.
582 return (x << - distance) | (x >>> distance);
586 * Find the highest set bit in value, and return a new value
587 * with only that bit set.
588 * @param value the value to examine
589 * @since 1.5
591 public static int highestOneBit(int value)
593 value |= value >>> 1;
594 value |= value >>> 2;
595 value |= value >>> 4;
596 value |= value >>> 8;
597 value |= value >>> 16;
598 return value ^ (value >>> 1);
602 * Return the number of leading zeros in value.
603 * @param value the value to examine
604 * @since 1.5
606 public static int numberOfLeadingZeros(int value)
608 value |= value >>> 1;
609 value |= value >>> 2;
610 value |= value >>> 4;
611 value |= value >>> 8;
612 value |= value >>> 16;
613 return bitCount(~value);
617 * Find the lowest set bit in value, and return a new value
618 * with only that bit set.
619 * @param value the value to examine
620 * @since 1.5
622 public static int lowestOneBit(int value)
624 // Classic assembly trick.
625 return value & - value;
629 * Find the number of trailing zeros in value.
630 * @param value the value to examine
631 * @since 1.5
633 public static int numberOfTrailingZeros(int value)
635 return bitCount((value & -value) - 1);
639 * Return 1 if x is positive, -1 if it is negative, and 0 if it is
640 * zero.
641 * @param x the value to examine
642 * @since 1.5
644 public static int signum(int x)
646 return x < 0 ? -1 : (x > 0 ? 1 : 0);
650 * Reverse the bytes in val.
651 * @since 1.5
653 public static int reverseBytes(int val)
655 return ( ((val >> 24) & 0xff)
656 | ((val >> 8) & 0xff00)
657 | ((val << 8) & 0xff0000)
658 | ((val << 24) & 0xff000000));
662 * Reverse the bits in val.
663 * @since 1.5
665 public static int reverse(int val)
667 // Successively swap alternating bit groups.
668 val = ((val >> 1) & 0x55555555) + ((val << 1) & ~0x55555555);
669 val = ((val >> 2) & 0x33333333) + ((val << 2) & ~0x33333333);
670 val = ((val >> 4) & 0x0f0f0f0f) + ((val << 4) & ~0x0f0f0f0f);
671 val = ((val >> 8) & 0x00ff00ff) + ((val << 8) & ~0x00ff00ff);
672 return ((val >> 16) & 0x0000ffff) + ((val << 16) & ~0x0000ffff);
676 * Helper for converting unsigned numbers to String.
678 * @param num the number
679 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
681 // Package visible for use by Long.
682 static String toUnsignedString(int num, int exp)
684 // Use an array large enough for a binary number.
685 int mask = (1 << exp) - 1;
686 char[] buffer = new char[32];
687 int i = 32;
690 buffer[--i] = digits[num & mask];
691 num >>>= exp;
693 while (num != 0);
695 // Package constructor avoids an array copy.
696 return new String(buffer, i, 32 - i, true);
700 * Helper for parsing ints, used by Integer, Short, and Byte.
702 * @param str the string to parse
703 * @param radix the radix to use, must be 10 if decode is true
704 * @param decode if called from decode
705 * @return the parsed int value
706 * @throws NumberFormatException if there is an error
707 * @throws NullPointerException if decode is true and str if null
708 * @see #parseInt(String, int)
709 * @see #decode(String)
710 * @see Byte#parseByte(String, int)
711 * @see Short#parseShort(String, int)
713 static int parseInt(String str, int radix, boolean decode)
715 if (! decode && str == null)
716 throw new NumberFormatException();
717 int index = 0;
718 int len = str.length();
719 boolean isNeg = false;
720 if (len == 0)
721 throw new NumberFormatException("string length is null");
722 int ch = str.charAt(index);
723 if (ch == '-')
725 if (len == 1)
726 throw new NumberFormatException("pure '-'");
727 isNeg = true;
728 ch = str.charAt(++index);
730 if (decode)
732 if (ch == '0')
734 if (++index == len)
735 return 0;
736 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
738 radix = 16;
739 index++;
741 else
742 radix = 8;
744 else if (ch == '#')
746 radix = 16;
747 index++;
750 if (index == len)
751 throw new NumberFormatException("non terminated number: " + str);
753 int max = MAX_VALUE / radix;
754 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
755 // So instead we fake it.
756 if (isNeg && MAX_VALUE % radix == radix - 1)
757 ++max;
759 int val = 0;
760 while (index < len)
762 if (val < 0 || val > max)
763 throw new NumberFormatException("number overflow (pos=" + index + ") : " + str);
765 ch = Character.digit(str.charAt(index++), radix);
766 val = val * radix + ch;
767 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
768 throw new NumberFormatException("invalid character at position " + index + " in " + str);
770 return isNeg ? -val : val;