Merge from mainline (gomp-merge-2005-02-26).
[official-gcc.git] / libjava / java / lang / Integer.java
blobeddaea2292ad81493262a056da133d9a01ef8b77
1 /* Integer.java -- object wrapper for int
2 Copyright (C) 1998, 1999, 2001, 2002, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.lang;
41 /**
42 * Instances of class <code>Integer</code> represent primitive
43 * <code>int</code> values.
45 * Additionally, this class provides various helper functions and variables
46 * related to ints.
48 * @author Paul Fisher
49 * @author John Keiser
50 * @author Warren Levy
51 * @author Eric Blake (ebb9@email.byu.edu)
52 * @since 1.0
53 * @status updated to 1.4
55 public final class Integer extends Number implements Comparable
57 /**
58 * Compatible with JDK 1.0.2+.
60 private static final long serialVersionUID = 1360826667806852920L;
62 /**
63 * The minimum value an <code>int</code> can represent is -2147483648 (or
64 * -2<sup>31</sup>).
66 public static final int MIN_VALUE = 0x80000000;
68 /**
69 * The maximum value an <code>int</code> can represent is 2147483647 (or
70 * 2<sup>31</sup> - 1).
72 public static final int MAX_VALUE = 0x7fffffff;
74 /**
75 * The primitive type <code>int</code> is represented by this
76 * <code>Class</code> object.
77 * @since 1.1
79 public static final Class TYPE = VMClassLoader.getPrimitiveClass('I');
81 /**
82 * The immutable value of this Integer.
84 * @serial the wrapped int
86 private final int value;
88 /**
89 * Create an <code>Integer</code> object representing the value of the
90 * <code>int</code> argument.
92 * @param value the value to use
94 public Integer(int value)
96 this.value = value;
99 /**
100 * Create an <code>Integer</code> object representing the value of the
101 * argument after conversion to an <code>int</code>.
103 * @param s the string to convert
104 * @throws NumberFormatException if the String does not contain an int
105 * @see #valueOf(String)
107 public Integer(String s)
109 value = parseInt(s, 10, false);
113 * Converts the <code>int</code> to a <code>String</code> using
114 * the specified radix (base). If the radix exceeds
115 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
116 * is used instead. If the result is negative, the leading character is
117 * '-' ('\\u002D'). The remaining characters come from
118 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
120 * @param num the <code>int</code> to convert to <code>String</code>
121 * @param radix the radix (base) to use in the conversion
122 * @return the <code>String</code> representation of the argument
124 public static String toString(int num, int radix)
126 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
127 radix = 10;
129 // For negative numbers, print out the absolute value w/ a leading '-'.
130 // Use an array large enough for a binary number.
131 char[] buffer = new char[33];
132 int i = 33;
133 boolean isNeg = false;
134 if (num < 0)
136 isNeg = true;
137 num = -num;
139 // When the value is MIN_VALUE, it overflows when made positive
140 if (num < 0)
142 buffer[--i] = digits[(int) (-(num + radix) % radix)];
143 num = -(num / radix);
149 buffer[--i] = digits[num % radix];
150 num /= radix;
152 while (num > 0);
154 if (isNeg)
155 buffer[--i] = '-';
157 // Package constructor avoids an array copy.
158 return new String(buffer, i, 33 - i, true);
162 * Converts the <code>int</code> to a <code>String</code> assuming it is
163 * unsigned in base 16.
165 * @param i the <code>int</code> to convert to <code>String</code>
166 * @return the <code>String</code> representation of the argument
168 public static String toHexString(int i)
170 return toUnsignedString(i, 4);
174 * Converts the <code>int</code> to a <code>String</code> assuming it is
175 * unsigned in base 8.
177 * @param i the <code>int</code> to convert to <code>String</code>
178 * @return the <code>String</code> representation of the argument
180 public static String toOctalString(int i)
182 return toUnsignedString(i, 3);
186 * Converts the <code>int</code> to a <code>String</code> assuming it is
187 * unsigned in base 2.
189 * @param i the <code>int</code> to convert to <code>String</code>
190 * @return the <code>String</code> representation of the argument
192 public static String toBinaryString(int i)
194 return toUnsignedString(i, 1);
198 * Converts the <code>int</code> to a <code>String</code> and assumes
199 * a radix of 10.
201 * @param i the <code>int</code> to convert to <code>String</code>
202 * @return the <code>String</code> representation of the argument
203 * @see #toString(int, int)
205 public static String toString(int i)
207 // This is tricky: in libgcj, String.valueOf(int) is a fast native
208 // implementation. In Classpath it just calls back to
209 // Integer.toString(int, int).
210 return String.valueOf(i);
214 * Converts the specified <code>String</code> into an <code>int</code>
215 * using the specified radix (base). The string must not be <code>null</code>
216 * or empty. It may begin with an optional '-', which will negate the answer,
217 * provided that there are also valid digits. Each digit is parsed as if by
218 * <code>Character.digit(d, radix)</code>, and must be in the range
219 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
220 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
221 * Unlike Double.parseDouble, you may not have a leading '+'.
223 * @param str the <code>String</code> to convert
224 * @param radix the radix (base) to use in the conversion
225 * @return the <code>String</code> argument converted to <code>int</code>
226 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
227 * <code>int</code>
229 public static int parseInt(String str, int radix)
231 return parseInt(str, radix, false);
235 * Converts the specified <code>String</code> into an <code>int</code>.
236 * This function assumes a radix of 10.
238 * @param s the <code>String</code> to convert
239 * @return the <code>int</code> value of <code>s</code>
240 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
241 * <code>int</code>
242 * @see #parseInt(String, int)
244 public static int parseInt(String s)
246 return parseInt(s, 10, false);
250 * Creates a new <code>Integer</code> object using the <code>String</code>
251 * and specified radix (base).
253 * @param s the <code>String</code> to convert
254 * @param radix the radix (base) to convert with
255 * @return the new <code>Integer</code>
256 * @throws NumberFormatException if <code>s</code> cannot be parsed as an
257 * <code>int</code>
258 * @see #parseInt(String, int)
260 public static Integer valueOf(String s, int radix)
262 return new Integer(parseInt(s, radix, false));
266 * Creates a new <code>Integer</code> object using the <code>String</code>,
267 * assuming a radix of 10.
269 * @param s the <code>String</code> to convert
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 #Integer(String)
274 * @see #parseInt(String)
276 public static Integer valueOf(String s)
278 return new Integer(parseInt(s, 10, false));
282 * Return the value of this <code>Integer</code> as a <code>byte</code>.
284 * @return the byte value
286 public byte byteValue()
288 return (byte) value;
292 * Return the value of this <code>Integer</code> as a <code>short</code>.
294 * @return the short value
296 public short shortValue()
298 return (short) value;
302 * Return the value of this <code>Integer</code>.
303 * @return the int value
305 public int intValue()
307 return value;
311 * Return the value of this <code>Integer</code> as a <code>long</code>.
313 * @return the long value
315 public long longValue()
317 return value;
321 * Return the value of this <code>Integer</code> as a <code>float</code>.
323 * @return the float value
325 public float floatValue()
327 return value;
331 * Return the value of this <code>Integer</code> as a <code>double</code>.
333 * @return the double value
335 public double doubleValue()
337 return value;
341 * Converts the <code>Integer</code> value to a <code>String</code> and
342 * assumes a radix of 10.
344 * @return the <code>String</code> representation
346 public String toString()
348 return String.valueOf(value);
352 * Return a hashcode representing this Object. <code>Integer</code>'s hash
353 * code is simply its value.
355 * @return this Object's hash code
357 public int hashCode()
359 return value;
363 * Returns <code>true</code> if <code>obj</code> is an instance of
364 * <code>Integer</code> and represents the same int value.
366 * @param obj the object to compare
367 * @return whether these Objects are semantically equal
369 public boolean equals(Object obj)
371 return obj instanceof Integer && value == ((Integer) obj).value;
375 * Get the specified system property as an <code>Integer</code>. The
376 * <code>decode()</code> method will be used to interpret the value of
377 * the property.
379 * @param nm the name of the system property
380 * @return the system property as an <code>Integer</code>, or null if the
381 * property is not found or cannot be decoded
382 * @throws SecurityException if accessing the system property is forbidden
383 * @see System#getProperty(String)
384 * @see #decode(String)
386 public static Integer getInteger(String nm)
388 return getInteger(nm, null);
392 * Get the specified system property as an <code>Integer</code>, or use a
393 * default <code>int</code> value if the property is not found or is not
394 * decodable. The <code>decode()</code> method will be used to interpret
395 * the value of the property.
397 * @param nm the name of the system property
398 * @param val the default value
399 * @return the value of the system property, or the default
400 * @throws SecurityException if accessing the system property is forbidden
401 * @see System#getProperty(String)
402 * @see #decode(String)
404 public static Integer getInteger(String nm, int val)
406 Integer result = getInteger(nm, null);
407 return result == null ? new Integer(val) : result;
411 * Get the specified system property as an <code>Integer</code>, or use a
412 * default <code>Integer</code> value if the property is not found or is
413 * not decodable. The <code>decode()</code> method will be used to
414 * interpret the value of the property.
416 * @param nm the name of the system property
417 * @param def the default value
418 * @return the value of the system property, or the default
419 * @throws SecurityException if accessing the system property is forbidden
420 * @see System#getProperty(String)
421 * @see #decode(String)
423 public static Integer getInteger(String nm, Integer def)
425 if (nm == null || "".equals(nm))
426 return def;
427 nm = System.getProperty(nm);
428 if (nm == null)
429 return def;
432 return decode(nm);
434 catch (NumberFormatException e)
436 return def;
441 * Convert the specified <code>String</code> into an <code>Integer</code>.
442 * The <code>String</code> may represent decimal, hexadecimal, or
443 * octal numbers.
445 * <p>The extended BNF grammar is as follows:<br>
446 * <pre>
447 * <em>DecodableString</em>:
448 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
449 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
450 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
451 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
452 * <em>DecimalNumber</em>:
453 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
454 * <em>DecimalDigit</em>:
455 * <em>Character.digit(d, 10) has value 0 to 9</em>
456 * <em>OctalDigit</em>:
457 * <em>Character.digit(d, 8) has value 0 to 7</em>
458 * <em>DecimalDigit</em>:
459 * <em>Character.digit(d, 16) has value 0 to 15</em>
460 * </pre>
461 * Finally, the value must be in the range <code>MIN_VALUE</code> to
462 * <code>MAX_VALUE</code>, or an exception is thrown.
464 * @param str the <code>String</code> to interpret
465 * @return the value of the String as an <code>Integer</code>
466 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
467 * <code>int</code>
468 * @throws NullPointerException if <code>s</code> is null
469 * @since 1.2
471 public static Integer decode(String str)
473 return new Integer(parseInt(str, 10, true));
477 * Compare two Integers numerically by comparing their <code>int</code>
478 * values. The result is positive if the first is greater, negative if the
479 * second is greater, and 0 if the two are equal.
481 * @param i the Integer to compare
482 * @return the comparison
483 * @since 1.2
485 public int compareTo(Integer i)
487 if (value == i.value)
488 return 0;
489 // Returns just -1 or 1 on inequality; doing math might overflow.
490 return value > i.value ? 1 : -1;
494 * Behaves like <code>compareTo(Integer)</code> unless the Object
495 * is not an <code>Integer</code>.
497 * @param o the object to compare
498 * @return the comparison
499 * @throws ClassCastException if the argument is not an <code>Integer</code>
500 * @see #compareTo(Integer)
501 * @see Comparable
502 * @since 1.2
504 public int compareTo(Object o)
506 return compareTo((Integer) o);
510 * Helper for converting unsigned numbers to String.
512 * @param num the number
513 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
515 // Package visible for use by Long.
516 static String toUnsignedString(int num, int exp)
518 // Use an array large enough for a binary number.
519 int mask = (1 << exp) - 1;
520 char[] buffer = new char[32];
521 int i = 32;
524 buffer[--i] = digits[num & mask];
525 num >>>= exp;
527 while (num != 0);
529 // Package constructor avoids an array copy.
530 return new String(buffer, i, 32 - i, true);
534 * Helper for parsing ints, used by Integer, Short, and Byte.
536 * @param str the string to parse
537 * @param radix the radix to use, must be 10 if decode is true
538 * @param decode if called from decode
539 * @return the parsed int value
540 * @throws NumberFormatException if there is an error
541 * @throws NullPointerException if decode is true and str if null
542 * @see #parseInt(String, int)
543 * @see #decode(String)
544 * @see Byte#parseInt(String, int)
545 * @see Short#parseInt(String, int)
547 static int parseInt(String str, int radix, boolean decode)
549 if (! decode && str == null)
550 throw new NumberFormatException();
551 int index = 0;
552 int len = str.length();
553 boolean isNeg = false;
554 if (len == 0)
555 throw new NumberFormatException();
556 int ch = str.charAt(index);
557 if (ch == '-')
559 if (len == 1)
560 throw new NumberFormatException();
561 isNeg = true;
562 ch = str.charAt(++index);
564 if (decode)
566 if (ch == '0')
568 if (++index == len)
569 return 0;
570 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
572 radix = 16;
573 index++;
575 else
576 radix = 8;
578 else if (ch == '#')
580 radix = 16;
581 index++;
584 if (index == len)
585 throw new NumberFormatException();
587 int max = MAX_VALUE / radix;
588 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
589 // So instead we fake it.
590 if (isNeg && MAX_VALUE % radix == radix - 1)
591 ++max;
593 int val = 0;
594 while (index < len)
596 if (val < 0 || val > max)
597 throw new NumberFormatException();
599 ch = Character.digit(str.charAt(index++), radix);
600 val = val * radix + ch;
601 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
602 throw new NumberFormatException();
604 return isNeg ? -val : val;