Integer.java 17.6 KB
Newer Older
1 2
/* Integer.java -- object wrapper for int
   Copyright (C) 1998, 1999, 2001, 2002 Free Software Foundation, Inc.
Tom Tromey committed
3

4
This file is part of GNU Classpath.
Tom Tromey committed
5

6 7 8 9
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
10

11 12 13 14 15 16 17 18 19 20
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
37 38


Tom Tromey committed
39 40 41
package java.lang;

/**
42 43 44 45 46 47 48 49 50
 * Instances of class <code>Integer</code> represent primitive
 * <code>int</code> values.
 *
 * Additionally, this class provides various helper functions and variables
 * related to ints.
 *
 * @author Paul Fisher
 * @author John Keiser
 * @author Warren Levy
51 52 53
 * @author Eric Blake <ebb9@email.byu.edu>
 * @since 1.0
 * @status updated to 1.4
Tom Tromey committed
54 55 56
 */
public final class Integer extends Number implements Comparable
{
57 58 59
  /**
   * Compatible with JDK 1.0.2+.
   */
60 61
  private static final long serialVersionUID = 1360826667806852920L;

62
  /**
63 64
   * The minimum value an <code>int</code> can represent is -2147483648 (or
   * -2<sup>31</sup>).
65 66 67 68
   */
  public static final int MIN_VALUE = 0x80000000;

  /**
69 70
   * The maximum value an <code>int</code> can represent is 2147483647 (or
   * 2<sup>31</sup> - 1).
71 72 73 74
   */
  public static final int MAX_VALUE = 0x7fffffff;

  /**
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 87 88
   */
  private final int value;

  /**
89
   * Create an <code>Integer</code> object representing the value of the
90 91 92 93 94
   * <code>int</code> argument.
   *
   * @param value the value to use
   */
  public Integer(int value)
Tom Tromey committed
95
  {
96
    this.value = value;
Tom Tromey committed
97 98
  }

99
  /**
100
   * Create an <code>Integer</code> object representing the value of the
101 102
   * argument after conversion to an <code>int</code>.
   *
103 104 105
   * @param s the string to convert
   * @throws NumberFormatException if the String does not contain an int
   * @see #valueOf(String)
106
   */
107
  public Integer(String s)
Tom Tromey committed
108
  {
109
    value = parseInt(s, 10, false);
Tom Tromey committed
110 111
  }

112
  /**
113 114 115 116 117 118
   * Converts the <code>int</code> to a <code>String</code> using
   * the specified radix (base). If the radix exceeds
   * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
   * is used instead. If the result is negative, the leading character is
   * '-' ('\\u002D'). The remaining characters come from
   * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
119
   *
120 121 122
   * @param num the <code>int</code> to convert to <code>String</code>
   * @param radix the radix (base) to use in the conversion
   * @return the <code>String</code> representation of the argument
123
   */
124
  public static String toString(int num, int radix)
Tom Tromey committed
125
  {
126 127
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
      radix = 10;
Tom Tromey committed
128

129 130 131 132 133 134
    // For negative numbers, print out the absolute value w/ a leading '-'.
    // Use an array large enough for a binary number.
    char[] buffer = new char[33];
    int i = 33;
    boolean isNeg = false;
    if (num < 0)
135
      {
136 137 138 139 140 141 142 143 144
        isNeg = true;
        num = -num;

        // When the value is MIN_VALUE, it overflows when made positive
        if (num < 0)
	  {
	    buffer[--i] = digits[(int) (-(num + radix) % radix)];
	    num = -(num / radix);
	  }
145
      }
Tom Tromey committed
146

147 148
    do
      {
149 150
        buffer[--i] = digits[num % radix];
        num /= radix;
151
      }
152
    while (num > 0);
153

154 155 156 157 158
    if (isNeg)
      buffer[--i] = '-';

    // Package constructor avoids an array copy.
    return new String(buffer, i, 33 - i, true);
Tom Tromey committed
159 160
  }

161 162 163
  /**
   * Converts the <code>int</code> to a <code>String</code> assuming it is
   * 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)
Tom Tromey committed
169
  {
170 171
    return toUnsignedString(i, 4);
  }
Tom Tromey committed
172

173 174 175
  /**
   * Converts the <code>int</code> to a <code>String</code> assuming it is
   * 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 181 182 183
   */
  public static String toOctalString(int i)
  {
    return toUnsignedString(i, 3);
  }
Tom Tromey committed
184

185 186 187
  /**
   * Converts the <code>int</code> to a <code>String</code> assuming it is
   * 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 193 194
   */
  public static String toBinaryString(int i)
  {
    return toUnsignedString(i, 1);
Tom Tromey committed
195 196
  }

197 198 199
  /**
   * Converts the <code>int</code> to a <code>String</code> and assumes
   * a radix of 10.
200
   *
201
   * @param i the <code>int</code> to convert to <code>String</code>
202 203
   * @return the <code>String</code> representation of the argument
   * @see #toString(int, int)
204 205
   */
  public static String toString(int i)
Tom Tromey committed
206
  {
207 208
    // This is tricky: in libgcj, String.valueOf(int) is a fast native
    // implementation.  In Classpath it just calls back to
209 210
    // Integer.toString(int, int).
    return String.valueOf(i);
Tom Tromey committed
211 212
  }

213
  /**
214 215 216 217 218 219 220 221 222
   * Converts the specified <code>String</code> into an <code>int</code>
   * using the specified radix (base). The string must not be <code>null</code>
   * or empty. It may begin with an optional '-', which will negate the answer,
   * provided that there are also valid digits. Each digit is parsed as if by
   * <code>Character.digit(d, radix)</code>, and must be in the range
   * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
   * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
   * 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 227
   * @throws NumberFormatException if <code>s</code> cannot be parsed as an
   *         <code>int</code>
228
   */
229
  public static int parseInt(String str, int radix)
230
  {
231
    return parseInt(str, radix, false);
Tom Tromey committed
232 233
  }

234
  /**
235 236 237 238 239 240 241 242 243 244
   * Converts the specified <code>String</code> into an <code>int</code>.
   * This function assumes a radix of 10.
   *
   * @param s the <code>String</code> to convert
   * @return the <code>int</code> value of <code>s</code>
   * @throws NumberFormatException if <code>s</code> cannot be parsed as an
   *         <code>int</code>
   * @see #parseInt(String, int)
   */
  public static int parseInt(String s)
Tom Tromey committed
245
  {
246
    return parseInt(s, 10, false);
Tom Tromey committed
247 248
  }

249 250 251
  /**
   * Creates a new <code>Integer</code> object using the <code>String</code>
   * and specified radix (base).
252 253 254 255 256 257 258
   *
   * @param s the <code>String</code> to convert
   * @param radix the radix (base) to convert with
   * @return the new <code>Integer</code>
   * @throws NumberFormatException if <code>s</code> cannot be parsed as an
   *         <code>int</code>
   * @see #parseInt(String, int)
259 260
   */
  public static Integer valueOf(String s, int radix)
Tom Tromey committed
261
  {
262
    return new Integer(parseInt(s, radix, false));
Tom Tromey committed
263 264
  }

265
  /**
266 267
   * Creates a new <code>Integer</code> object using the <code>String</code>,
   * assuming a radix of 10.
268 269
   *
   * @param s the <code>String</code> to convert
270 271 272 273 274
   * @return the new <code>Integer</code>
   * @throws NumberFormatException if <code>s</code> cannot be parsed as an
   *         <code>int</code>
   * @see #Integer(String)
   * @see #parseInt(String)
275
   */
276
  public static Integer valueOf(String s)
Tom Tromey committed
277
  {
278
    return new Integer(parseInt(s, 10, false));
Tom Tromey committed
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()
Tom Tromey committed
287
  {
288
    return (byte) value;
Tom Tromey committed
289 290
  }

291 292 293 294 295 296
  /**
   * Return the value of this <code>Integer</code> as a <code>short</code>.
   *
   * @return the short value
   */
  public short shortValue()
Tom Tromey committed
297
  {
298 299
    return (short) value;
  }
Tom Tromey committed
300

301 302 303 304 305 306 307
  /**
   * Return the value of this <code>Integer</code>.
   * @return the int value
   */
  public int intValue()
  {
    return value;
Tom Tromey committed
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()
Tom Tromey committed
316
  {
317 318
    return value;
  }
319

320 321 322 323 324 325 326 327 328
  /**
   * Return the value of this <code>Integer</code> as a <code>float</code>.
   *
   * @return the float value
   */
  public float floatValue()
  {
    return value;
  }
329

330 331 332 333 334 335 336 337 338
  /**
   * Return the value of this <code>Integer</code> as a <code>double</code>.
   *
   * @return the double value
   */
  public double doubleValue()
  {
    return value;
  }
339

340 341 342 343 344 345 346 347 348
  /**
   * Converts the <code>Integer</code> value to a <code>String</code> and
   * assumes a radix of 10.
   *
   * @return the <code>String</code> representation
   */
  public String toString()
  {
    return String.valueOf(value);
Tom Tromey committed
349 350
  }

351 352 353 354 355 356 357
  /**
   * Return a hashcode representing this Object. <code>Integer</code>'s hash
   * code is simply its value.
   *
   * @return this Object's hash code
   */
  public int hashCode()
Tom Tromey committed
358
  {
359
    return value;
Tom Tromey committed
360 361
  }

362 363 364 365 366 367 368 369
  /**
   * Returns <code>true</code> if <code>obj</code> is an instance of
   * <code>Integer</code> and represents the same int value.
   *
   * @param obj the object to compare
   * @return whether these Objects are semantically equal
   */
  public boolean equals(Object obj)
Tom Tromey committed
370
  {
371
    return obj instanceof Integer && value == ((Integer) obj).value;
Tom Tromey committed
372 373
  }

374 375 376 377 378 379 380 381 382 383 384 385 386
  /**
   * Get the specified system property as an <code>Integer</code>. The
   * <code>decode()</code> method will be used to interpret the value of
   * the property.
   *
   * @param nm the name of the system property
   * @return the system property as an <code>Integer</code>, or null if the
   *         property is not found or cannot be decoded
   * @throws SecurityException if accessing the system property is forbidden
   * @see System#getProperty(String)
   * @see #decode(String)
   */
  public static Integer getInteger(String nm)
Tom Tromey committed
387
  {
388
    return getInteger(nm, null);
Tom Tromey committed
389 390
  }

391 392 393 394 395 396 397 398 399 400 401 402 403 404
  /**
   * Get the specified system property as an <code>Integer</code>, or use a
   * default <code>int</code> value if the property is not found or is not
   * decodable. The <code>decode()</code> method will be used to interpret
   * the value of the property.
   *
   * @param nm the name of the system property
   * @param val the default value
   * @return the value of the system property, or the default
   * @throws SecurityException if accessing the system property is forbidden
   * @see System#getProperty(String)
   * @see #decode(String)
   */
  public static Integer getInteger(String nm, int val)
Tom Tromey committed
405
  {
406 407
    Integer result = getInteger(nm, null);
    return result == null ? new Integer(val) : result;
Tom Tromey committed
408 409
  }

410 411 412 413 414 415 416
  /**
   * Get the specified system property as an <code>Integer</code>, or use a
   * default <code>Integer</code> value if the property is not found or is
   * not decodable. The <code>decode()</code> method will be used to
   * interpret the value of the property.
   *
   * @param nm the name of the system property
417
   * @param def the default value
418 419 420 421 422 423
   * @return the value of the system property, or the default
   * @throws SecurityException if accessing the system property is forbidden
   * @see System#getProperty(String)
   * @see #decode(String)
   */
  public static Integer getInteger(String nm, Integer def)
Tom Tromey committed
424
  {
425 426 427 428 429 430 431 432 433 434 435 436 437
    if (nm == null || "".equals(nm))
      return def;
    nm = System.getProperty(nm);
    if (nm == null)
      return def;
    try
      {
        return decode(nm);
      }
    catch (NumberFormatException e)
      {
        return def;
      }
Tom Tromey committed
438 439
  }

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  /**
   * Convert the specified <code>String</code> into an <code>Integer</code>.
   * The <code>String</code> may represent decimal, hexadecimal, or
   * octal numbers.
   *
   * <p>The extended BNF grammar is as follows:<br>
   * <pre>
   * <em>DecodableString</em>:
   *      ( [ <code>-</code> ] <em>DecimalNumber</em> )
   *    | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
   *              | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
   *    | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
   * <em>DecimalNumber</em>:
   *        <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
   * <em>DecimalDigit</em>:
   *        <em>Character.digit(d, 10) has value 0 to 9</em>
   * <em>OctalDigit</em>:
   *        <em>Character.digit(d, 8) has value 0 to 7</em>
   * <em>DecimalDigit</em>:
   *        <em>Character.digit(d, 16) has value 0 to 15</em>
   * </pre>
   * Finally, the value must be in the range <code>MIN_VALUE</code> to
   * <code>MAX_VALUE</code>, or an exception is thrown.
   *
464
   * @param str the <code>String</code> to interpret
465 466 467 468 469 470 471
   * @return the value of the String as an <code>Integer</code>
   * @throws NumberFormatException if <code>s</code> cannot be parsed as a
   *         <code>int</code>
   * @throws NullPointerException if <code>s</code> is null
   * @since 1.2
   */
  public static Integer decode(String str)
Tom Tromey committed
472
  {
473
    return new Integer(parseInt(str, 10, true));
Tom Tromey committed
474 475
  }

476
  /**
477 478 479
   * Compare two Integers numerically by comparing their <code>int</code>
   * values. The result is positive if the first is greater, negative if the
   * second is greater, and 0 if the two are equal.
480
   *
481 482
   * @param i the Integer to compare
   * @return the comparison
483 484 485
   * @since 1.2
   */
  public int compareTo(Integer i)
Tom Tromey committed
486
  {
487
    if (value == i.value)
488 489
      return 0;
    // Returns just -1 or 1 on inequality; doing math might overflow.
490
    return value > i.value ? 1 : -1;
Tom Tromey committed
491 492
  }

493
  /**
494 495
   * Behaves like <code>compareTo(Integer)</code> unless the Object
   * is not an <code>Integer</code>.
496
   *
497 498 499 500 501
   * @param o the object to compare
   * @return the comparison
   * @throws ClassCastException if the argument is not an <code>Integer</code>
   * @see #compareTo(Integer)
   * @see Comparable
502 503 504
   * @since 1.2
   */
  public int compareTo(Object o)
Tom Tromey committed
505
  {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    return compareTo((Integer) o);
  }

  /**
   * Helper for converting unsigned numbers to String.
   *
   * @param num the number
   * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
   */
  // Package visible for use by Long.
  static String toUnsignedString(int num, int exp)
  {
    // Use an array large enough for a binary number.
    int mask = (1 << exp) - 1;
    char[] buffer = new char[32];
    int i = 32;
    do
      {
        buffer[--i] = digits[num & mask];
        num >>>= exp;
      }
    while (num != 0);

    // Package constructor avoids an array copy.
    return new String(buffer, i, 32 - i, true);
  }

  /**
   * Helper for parsing ints, used by Integer, Short, and Byte.
   *
   * @param str the string to parse
   * @param radix the radix to use, must be 10 if decode is true
   * @param decode if called from decode
   * @return the parsed int value
   * @throws NumberFormatException if there is an error
   * @throws NullPointerException if decode is true and str if null
   * @see #parseInt(String, int)
   * @see #decode(String)
   * @see Byte#parseInt(String, int)
   * @see Short#parseInt(String, int)
   */
  static int parseInt(String str, int radix, boolean decode)
  {
    if (! decode && str == null)
      throw new NumberFormatException();
    int index = 0;
    int len = str.length();
    boolean isNeg = false;
    if (len == 0)
      throw new NumberFormatException();
    int ch = str.charAt(index);
    if (ch == '-')
      {
        if (len == 1)
          throw new NumberFormatException();
        isNeg = true;
        ch = str.charAt(++index);
      }
    if (decode)
      {
        if (ch == '0')
          {
            if (++index == len)
              return 0;
            if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
              {
                radix = 16;
                index++;
              }
            else
              radix = 8;
          }
        else if (ch == '#')
          {
            radix = 16;
            index++;
          }
      }
    if (index == len)
      throw new NumberFormatException();

    int max = MAX_VALUE / radix;
    // We can't directly write `max = (MAX_VALUE + 1) / radix'.
    // So instead we fake it.
    if (isNeg && MAX_VALUE % radix == radix - 1)
      ++max;

    int val = 0;
    while (index < len)
      {
	if (val < 0 || val > max)
	  throw new NumberFormatException();

        ch = Character.digit(str.charAt(index++), radix);
        val = val * radix + ch;
        if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
          throw new NumberFormatException();
      }
    return isNeg ? -val : val;
Tom Tromey committed
605 606
  }
}