source: trunk/gcc/libjava/java/lang/Integer.java

Last change on this file was 1392, checked in by bird, 21 years ago

This commit was generated by cvs2svn to compensate for changes in r1391,
which included commits to RCS files with non-trunk default branches.

  • Property cvs2svn:cvs-rev set to 1.1.1.2
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 17.6 KB
Line 
1/* Integer.java -- object wrapper for int
2 Copyright (C) 1998, 1999, 2001, 2002 Free Software Foundation, Inc.
3
4This file is part of GNU Classpath.
5
6GNU Classpath is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 2, or (at your option)
9any later version.
10
11GNU Classpath is distributed in the hope that it will be useful, but
12WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Classpath; see the file COPYING. If not, write to the
18Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
1902111-1307 USA.
20
21Linking this library statically or dynamically with other modules is
22making a combined work based on this library. Thus, the terms and
23conditions of the GNU General Public License cover the whole
24combination.
25
26As a special exception, the copyright holders of this library give you
27permission to link this library with independent modules to produce an
28executable, regardless of the license terms of these independent
29modules, and to copy and distribute the resulting executable under
30terms of your choice, provided that you also meet, for each linked
31independent module, the terms and conditions of the license of that
32module. An independent module is a module which is not derived from
33or based on this library. If you modify this library, you may extend
34this exception to your version of the library, but you are not
35obligated to do so. If you do not wish to do so, delete this
36exception statement from your version. */
37
38
39package java.lang;
40
41/**
42 * Instances of class <code>Integer</code> represent primitive
43 * <code>int</code> values.
44 *
45 * Additionally, this class provides various helper functions and variables
46 * related to ints.
47 *
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
54 */
55public final class Integer extends Number implements Comparable
56{
57 /**
58 * Compatible with JDK 1.0.2+.
59 */
60 private static final long serialVersionUID = 1360826667806852920L;
61
62 /**
63 * The minimum value an <code>int</code> can represent is -2147483648 (or
64 * -2<sup>31</sup>).
65 */
66 public static final int MIN_VALUE = 0x80000000;
67
68 /**
69 * The maximum value an <code>int</code> can represent is 2147483647 (or
70 * 2<sup>31</sup> - 1).
71 */
72 public static final int MAX_VALUE = 0x7fffffff;
73
74 /**
75 * The primitive type <code>int</code> is represented by this
76 * <code>Class</code> object.
77 * @since 1.1
78 */
79 public static final Class TYPE = VMClassLoader.getPrimitiveClass('I');
80
81 /**
82 * The immutable value of this Integer.
83 *
84 * @serial the wrapped int
85 */
86 private final int value;
87
88 /**
89 * Create an <code>Integer</code> object representing the value of the
90 * <code>int</code> argument.
91 *
92 * @param value the value to use
93 */
94 public Integer(int value)
95 {
96 this.value = value;
97 }
98
99 /**
100 * Create an <code>Integer</code> object representing the value of the
101 * argument after conversion to an <code>int</code>.
102 *
103 * @param s the string to convert
104 * @throws NumberFormatException if the String does not contain an int
105 * @see #valueOf(String)
106 */
107 public Integer(String s)
108 {
109 value = parseInt(s, 10, false);
110 }
111
112 /**
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').
119 *
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
123 */
124 public static String toString(int num, int radix)
125 {
126 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
127 radix = 10;
128
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)
135 {
136 isNeg = true;
137 num = -num;
138
139 // When the value is MIN_VALUE, it overflows when made positive
140 if (num < 0)
141 {
142 buffer[--i] = digits[(int) (-(num + radix) % radix)];
143 num = -(num / radix);
144 }
145 }
146
147 do
148 {
149 buffer[--i] = digits[num % radix];
150 num /= radix;
151 }
152 while (num > 0);
153
154 if (isNeg)
155 buffer[--i] = '-';
156
157 // Package constructor avoids an array copy.
158 return new String(buffer, i, 33 - i, true);
159 }
160
161 /**
162 * Converts the <code>int</code> to a <code>String</code> assuming it is
163 * unsigned in base 16.
164 *
165 * @param i the <code>int</code> to convert to <code>String</code>
166 * @return the <code>String</code> representation of the argument
167 */
168 public static String toHexString(int i)
169 {
170 return toUnsignedString(i, 4);
171 }
172
173 /**
174 * Converts the <code>int</code> to a <code>String</code> assuming it is
175 * unsigned in base 8.
176 *
177 * @param i the <code>int</code> to convert to <code>String</code>
178 * @return the <code>String</code> representation of the argument
179 */
180 public static String toOctalString(int i)
181 {
182 return toUnsignedString(i, 3);
183 }
184
185 /**
186 * Converts the <code>int</code> to a <code>String</code> assuming it is
187 * unsigned in base 2.
188 *
189 * @param i the <code>int</code> to convert to <code>String</code>
190 * @return the <code>String</code> representation of the argument
191 */
192 public static String toBinaryString(int i)
193 {
194 return toUnsignedString(i, 1);
195 }
196
197 /**
198 * Converts the <code>int</code> to a <code>String</code> and assumes
199 * a radix of 10.
200 *
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)
204 */
205 public static String toString(int i)
206 {
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);
211 }
212
213 /**
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 '+'.
222 *
223 * @param s 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>
228 */
229 public static int parseInt(String str, int radix)
230 {
231 return parseInt(str, radix, false);
232 }
233
234 /**
235 * Converts the specified <code>String</code> into an <code>int</code>.
236 * This function assumes a radix of 10.
237 *
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)
243 */
244 public static int parseInt(String s)
245 {
246 return parseInt(s, 10, false);
247 }
248
249 /**
250 * Creates a new <code>Integer</code> object using the <code>String</code>
251 * and specified radix (base).
252 *
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)
259 */
260 public static Integer valueOf(String s, int radix)
261 {
262 return new Integer(parseInt(s, radix, false));
263 }
264
265 /**
266 * Creates a new <code>Integer</code> object using the <code>String</code>,
267 * assuming a radix of 10.
268 *
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)
275 */
276 public static Integer valueOf(String s)
277 {
278 return new Integer(parseInt(s, 10, false));
279 }
280
281 /**
282 * Return the value of this <code>Integer</code> as a <code>byte</code>.
283 *
284 * @return the byte value
285 */
286 public byte byteValue()
287 {
288 return (byte) value;
289 }
290
291 /**
292 * Return the value of this <code>Integer</code> as a <code>short</code>.
293 *
294 * @return the short value
295 */
296 public short shortValue()
297 {
298 return (short) value;
299 }
300
301 /**
302 * Return the value of this <code>Integer</code>.
303 * @return the int value
304 */
305 public int intValue()
306 {
307 return value;
308 }
309
310 /**
311 * Return the value of this <code>Integer</code> as a <code>long</code>.
312 *
313 * @return the long value
314 */
315 public long longValue()
316 {
317 return value;
318 }
319
320 /**
321 * Return the value of this <code>Integer</code> as a <code>float</code>.
322 *
323 * @return the float value
324 */
325 public float floatValue()
326 {
327 return value;
328 }
329
330 /**
331 * Return the value of this <code>Integer</code> as a <code>double</code>.
332 *
333 * @return the double value
334 */
335 public double doubleValue()
336 {
337 return value;
338 }
339
340 /**
341 * Converts the <code>Integer</code> value to a <code>String</code> and
342 * assumes a radix of 10.
343 *
344 * @return the <code>String</code> representation
345 */
346 public String toString()
347 {
348 return String.valueOf(value);
349 }
350
351 /**
352 * Return a hashcode representing this Object. <code>Integer</code>'s hash
353 * code is simply its value.
354 *
355 * @return this Object's hash code
356 */
357 public int hashCode()
358 {
359 return value;
360 }
361
362 /**
363 * Returns <code>true</code> if <code>obj</code> is an instance of
364 * <code>Integer</code> and represents the same int value.
365 *
366 * @param obj the object to compare
367 * @return whether these Objects are semantically equal
368 */
369 public boolean equals(Object obj)
370 {
371 return obj instanceof Integer && value == ((Integer) obj).value;
372 }
373
374 /**
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.
378 *
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)
385 */
386 public static Integer getInteger(String nm)
387 {
388 return getInteger(nm, null);
389 }
390
391 /**
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.
396 *
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)
403 */
404 public static Integer getInteger(String nm, int val)
405 {
406 Integer result = getInteger(nm, null);
407 return result == null ? new Integer(val) : result;
408 }
409
410 /**
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.
415 *
416 * @param nm the name of the system property
417 * @param val 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)
422 */
423 public static Integer getInteger(String nm, Integer def)
424 {
425 if (nm == null || "".equals(nm))
426 return def;
427 nm = System.getProperty(nm);
428 if (nm == null)
429 return def;
430 try
431 {
432 return decode(nm);
433 }
434 catch (NumberFormatException e)
435 {
436 return def;
437 }
438 }
439
440 /**
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.
444 *
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.
463 *
464 * @param s 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
470 */
471 public static Integer decode(String str)
472 {
473 return new Integer(parseInt(str, 10, true));
474 }
475
476 /**
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.
480 *
481 * @param i the Integer to compare
482 * @return the comparison
483 * @since 1.2
484 */
485 public int compareTo(Integer i)
486 {
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;
491 }
492
493 /**
494 * Behaves like <code>compareTo(Integer)</code> unless the Object
495 * is not an <code>Integer</code>.
496 *
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
503 */
504 public int compareTo(Object o)
505 {
506 return compareTo((Integer) o);
507 }
508
509 /**
510 * Helper for converting unsigned numbers to String.
511 *
512 * @param num the number
513 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
514 */
515 // Package visible for use by Long.
516 static String toUnsignedString(int num, int exp)
517 {
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;
522 do
523 {
524 buffer[--i] = digits[num & mask];
525 num >>>= exp;
526 }
527 while (num != 0);
528
529 // Package constructor avoids an array copy.
530 return new String(buffer, i, 32 - i, true);
531 }
532
533 /**
534 * Helper for parsing ints, used by Integer, Short, and Byte.
535 *
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)
546 */
547 static int parseInt(String str, int radix, boolean decode)
548 {
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 == '-')
558 {
559 if (len == 1)
560 throw new NumberFormatException();
561 isNeg = true;
562 ch = str.charAt(++index);
563 }
564 if (decode)
565 {
566 if (ch == '0')
567 {
568 if (++index == len)
569 return 0;
570 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
571 {
572 radix = 16;
573 index++;
574 }
575 else
576 radix = 8;
577 }
578 else if (ch == '#')
579 {
580 radix = 16;
581 index++;
582 }
583 }
584 if (index == len)
585 throw new NumberFormatException();
586
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;
592
593 int val = 0;
594 while (index < len)
595 {
596 if (val < 0 || val > max)
597 throw new NumberFormatException();
598
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();
603 }
604 return isNeg ? -val : val;
605 }
606}
Note: See TracBrowser for help on using the repository browser.