FSF GCC merge 02/23/03
[official-gcc.git] / libjava / java / lang / Long.java
blob1420e58d6c4763db9c7449dc9bd58c28e82a4b4c
1 /* Long.java -- object wrapper for long
2 Copyright (C) 1998, 1999, 2001, 2002 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>Long</code> represent primitive
43 * <code>long</code> values.
45 * Additionally, this class provides various helper functions and variables
46 * related to longs.
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 Long extends Number implements Comparable
57 /**
58 * Compatible with JDK 1.0.2+.
60 private static final long serialVersionUID = 4290774380558885855L;
62 /**
63 * The minimum value a <code>long</code> can represent is
64 * -9223372036854775808L (or -2<sup>63</sup>).
66 public static final long MIN_VALUE = 0x8000000000000000L;
68 /**
69 * The maximum value a <code>long</code> can represent is
70 * 9223372036854775807 (or 2<sup>63</sup> - 1).
72 public static final long MAX_VALUE = 0x7fffffffffffffffL;
74 /**
75 * The primitive type <code>long</code> is represented by this
76 * <code>Class</code> object.
77 * @since 1.1
79 public static final Class TYPE = VMClassLoader.getPrimitiveClass ('J');
81 /**
82 * The immutable value of this Long.
84 * @serial the wrapped long
86 private final long value;
88 /**
89 * Create a <code>Long</code> object representing the value of the
90 * <code>long</code> argument.
92 * @param value the value to use
94 public Long(long value)
96 this.value = value;
99 /**
100 * Create a <code>Long</code> object representing the value of the
101 * argument after conversion to a <code>long</code>.
103 * @param s the string to convert
104 * @throws NumberFormatException if the String does not contain a long
105 * @see #valueOf(String)
107 public Long(String s)
109 value = parseLong(s, 10, false);
113 * Converts the <code>long</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>long</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(long num, int radix)
126 // Use the Integer toString for efficiency if possible.
127 if ((int) num == num)
128 return Integer.toString((int) num, radix);
130 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
131 radix = 10;
133 // For negative numbers, print out the absolute value w/ a leading '-'.
134 // Use an array large enough for a binary number.
135 char[] buffer = new char[65];
136 int i = 65;
137 boolean isNeg = false;
138 if (num < 0)
140 isNeg = true;
141 num = -num;
143 // When the value is MIN_VALUE, it overflows when made positive
144 if (num < 0)
146 buffer[--i] = digits[(int) (-(num + radix) % radix)];
147 num = -(num / radix);
153 buffer[--i] = digits[(int) (num % radix)];
154 num /= radix;
156 while (num > 0);
158 if (isNeg)
159 buffer[--i] = '-';
161 // Package constructor avoids an array copy.
162 return new String(buffer, i, 65 - i, true);
166 * Converts the <code>long</code> to a <code>String</code> assuming it is
167 * unsigned in base 16.
169 * @param l the <code>long</code> to convert to <code>String</code>
170 * @return the <code>String</code> representation of the argument
172 public static String toHexString(long l)
174 return toUnsignedString(l, 4);
178 * Converts the <code>long</code> to a <code>String</code> assuming it is
179 * unsigned in base 8.
181 * @param l the <code>long</code> to convert to <code>String</code>
182 * @return the <code>String</code> representation of the argument
184 public static String toOctalString(long l)
186 return toUnsignedString(l, 3);
190 * Converts the <code>long</code> to a <code>String</code> assuming it is
191 * unsigned in base 2.
193 * @param l the <code>long</code> to convert to <code>String</code>
194 * @return the <code>String</code> representation of the argument
196 public static String toBinaryString(long l)
198 return toUnsignedString(l, 1);
202 * Converts the <code>long</code> to a <code>String</code> and assumes
203 * a radix of 10.
205 * @param num the <code>long</code> to convert to <code>String</code>
206 * @return the <code>String</code> representation of the argument
207 * @see #toString(long, int)
209 public static String toString(long num)
211 return toString(num, 10);
215 * Converts the specified <code>String</code> into an <code>int</code>
216 * using the specified radix (base). The string must not be <code>null</code>
217 * or empty. It may begin with an optional '-', which will negate the answer,
218 * provided that there are also valid digits. Each digit is parsed as if by
219 * <code>Character.digit(d, radix)</code>, and must be in the range
220 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
221 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
222 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
223 * 'L' as the last character is only valid in radices 22 or greater, where
224 * it is a digit and not a type indicator.
226 * @param s the <code>String</code> to convert
227 * @param radix the radix (base) to use in the conversion
228 * @return the <code>String</code> argument converted to </code>long</code>
229 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
230 * <code>long</code>
232 public static long parseLong(String str, int radix)
234 return parseLong(str, radix, false);
238 * Converts the specified <code>String</code> into a <code>long</code>.
239 * This function assumes a radix of 10.
241 * @param s the <code>String</code> to convert
242 * @return the <code>int</code> value of <code>s</code>
243 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
244 * <code>long</code>
245 * @see #parseLong(String, int)
247 public static long parseLong(String s)
249 return parseLong(s, 10, false);
253 * Creates a new <code>Long</code> object using the <code>String</code>
254 * and specified radix (base).
256 * @param s the <code>String</code> to convert
257 * @param radix the radix (base) to convert with
258 * @return the new <code>Long</code>
259 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
260 * <code>long</code>
261 * @see #parseLong(String, int)
263 public static Long valueOf(String s, int radix)
265 return new Long(parseLong(s, radix, false));
269 * Creates a new <code>Long</code> object using the <code>String</code>,
270 * assuming a radix of 10.
272 * @param s the <code>String</code> to convert
273 * @return the new <code>Long</code>
274 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
275 * <code>long</code>
276 * @see #Long(String)
277 * @see #parseLong(String)
279 public static Long valueOf(String s)
281 return new Long(parseLong(s, 10, false));
285 * Convert the specified <code>String</code> into a <code>Long</code>.
286 * The <code>String</code> may represent decimal, hexadecimal, or
287 * octal numbers.
289 * <p>The extended BNF grammar is as follows:<br>
290 * <pre>
291 * <em>DecodableString</em>:
292 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
293 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
294 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
295 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
296 * <em>DecimalNumber</em>:
297 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
298 * <em>DecimalDigit</em>:
299 * <em>Character.digit(d, 10) has value 0 to 9</em>
300 * <em>OctalDigit</em>:
301 * <em>Character.digit(d, 8) has value 0 to 7</em>
302 * <em>DecimalDigit</em>:
303 * <em>Character.digit(d, 16) has value 0 to 15</em>
304 * </pre>
305 * Finally, the value must be in the range <code>MIN_VALUE</code> to
306 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
307 * use a trailing 'l' or 'L', unlike in Java source code.
309 * @param s the <code>String</code> to interpret
310 * @return the value of the String as a <code>Long</code>
311 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
312 * <code>long</code>
313 * @throws NullPointerException if <code>s</code> is null
314 * @since 1.2
316 public static Long decode(String str)
318 return new Long(parseLong(str, 10, true));
322 * Return the value of this <code>Long</code> as a <code>byte</code>.
324 * @return the byte value
326 public byte byteValue()
328 return (byte) value;
332 * Return the value of this <code>Long</code> as a <code>short</code>.
334 * @return the short value
336 public short shortValue()
338 return (short) value;
342 * Return the value of this <code>Long</code> as an <code>int</code>.
344 * @return the int value
346 public int intValue()
348 return (int) value;
352 * Return the value of this <code>Long</code>.
354 * @return the long value
356 public long longValue()
358 return value;
362 * Return the value of this <code>Long</code> as a <code>float</code>.
364 * @return the float value
366 public float floatValue()
368 return value;
372 * Return the value of this <code>Long</code> as a <code>double</code>.
374 * @return the double value
376 public double doubleValue()
378 return value;
382 * Converts the <code>Long</code> value to a <code>String</code> and
383 * assumes a radix of 10.
385 * @return the <code>String</code> representation
387 public String toString()
389 return toString(value, 10);
393 * Return a hashcode representing this Object. <code>Long</code>'s hash
394 * code is calculated by <code>(int) (value ^ (value &gt;&gt; 32))</code>.
396 * @return this Object's hash code
398 public int hashCode()
400 return (int) (value ^ (value >>> 32));
404 * Returns <code>true</code> if <code>obj</code> is an instance of
405 * <code>Long</code> and represents the same long value.
407 * @param obj the object to compare
408 * @return whether these Objects are semantically equal
410 public boolean equals(Object obj)
412 return obj instanceof Long && value == ((Long) obj).value;
416 * Get the specified system property as a <code>Long</code>. The
417 * <code>decode()</code> method will be used to interpret the value of
418 * the property.
420 * @param nm the name of the system property
421 * @return the system property as a <code>Long</code>, or null if the
422 * property is not found or cannot be decoded
423 * @throws SecurityException if accessing the system property is forbidden
424 * @see System#getProperty(String)
425 * @see #decode(String)
427 public static Long getLong(String nm)
429 return getLong(nm, null);
433 * Get the specified system property as a <code>Long</code>, or use a
434 * default <code>long</code> value if the property is not found or is not
435 * decodable. The <code>decode()</code> method will be used to interpret
436 * the value of the property.
438 * @param nm the name of the system property
439 * @param val the default value
440 * @return the value of the system property, or the default
441 * @throws SecurityException if accessing the system property is forbidden
442 * @see System#getProperty(String)
443 * @see #decode(String)
445 public static Long getLong(String nm, long val)
447 Long result = getLong(nm, null);
448 return result == null ? new Long(val) : result;
452 * Get the specified system property as a <code>Long</code>, or use a
453 * default <code>Long</code> value if the property is not found or is
454 * not decodable. The <code>decode()</code> method will be used to
455 * interpret the value of the property.
457 * @param nm the name of the system property
458 * @param val the default value
459 * @return the value of the system property, or the default
460 * @throws SecurityException if accessing the system property is forbidden
461 * @see System#getProperty(String)
462 * @see #decode(String)
464 public static Long getLong(String nm, Long def)
466 if (nm == null || "".equals(nm))
467 return def;
468 nm = System.getProperty(nm);
469 if (nm == null)
470 return def;
473 return decode(nm);
475 catch (NumberFormatException e)
477 return def;
482 * Compare two Longs numerically by comparing their <code>long</code>
483 * values. The result is positive if the first is greater, negative if the
484 * second is greater, and 0 if the two are equal.
486 * @param l the Long to compare
487 * @return the comparison
488 * @since 1.2
490 public int compareTo(Long l)
492 if (value == l.value)
493 return 0;
494 // Returns just -1 or 1 on inequality; doing math might overflow the long.
495 return value > l.value ? 1 : -1;
499 * Behaves like <code>compareTo(Long)</code> unless the Object
500 * is not a <code>Long</code>.
502 * @param o the object to compare
503 * @return the comparison
504 * @throws ClassCastException if the argument is not a <code>Long</code>
505 * @see #compareTo(Long)
506 * @see Comparable
507 * @since 1.2
509 public int compareTo(Object o)
511 return compareTo((Long) o);
515 * Helper for converting unsigned numbers to String.
517 * @param num the number
518 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
520 private static String toUnsignedString(long num, int exp)
522 // Use the Integer toUnsignedString for efficiency if possible.
523 // If NUM<0 then this particular optimization doesn't work
524 // properly.
525 if (num >= 0 && (int) num == num)
526 return Integer.toUnsignedString((int) num, exp);
528 // Use an array large enough for a binary number.
529 int mask = (1 << exp) - 1;
530 char[] buffer = new char[64];
531 int i = 64;
534 buffer[--i] = digits[(int) num & mask];
535 num >>>= exp;
537 while (num != 0);
539 // Package constructor avoids an array copy.
540 return new String(buffer, i, 64 - i, true);
544 * Helper for parsing longs.
546 * @param str the string to parse
547 * @param radix the radix to use, must be 10 if decode is true
548 * @param decode if called from decode
549 * @return the parsed long value
550 * @throws NumberFormatException if there is an error
551 * @throws NullPointerException if decode is true and str is null
552 * @see #parseLong(String, int)
553 * @see #decode(String)
555 private static long parseLong(String str, int radix, boolean decode)
557 if (! decode && str == null)
558 throw new NumberFormatException();
559 int index = 0;
560 int len = str.length();
561 boolean isNeg = false;
562 if (len == 0)
563 throw new NumberFormatException();
564 int ch = str.charAt(index);
565 if (ch == '-')
567 if (len == 1)
568 throw new NumberFormatException();
569 isNeg = true;
570 ch = str.charAt(++index);
572 if (decode)
574 if (ch == '0')
576 if (++index == len)
577 return 0;
578 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
580 radix = 16;
581 index++;
583 else
584 radix = 8;
586 else if (ch == '#')
588 radix = 16;
589 index++;
592 if (index == len)
593 throw new NumberFormatException();
595 long max = MAX_VALUE / radix;
596 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
597 // So instead we fake it.
598 if (isNeg && MAX_VALUE % radix == radix - 1)
599 ++max;
601 long val = 0;
602 while (index < len)
604 if (val < 0 || val > max)
605 throw new NumberFormatException();
607 ch = Character.digit(str.charAt(index++), radix);
608 val = val * radix + ch;
609 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
610 throw new NumberFormatException();
612 return isNeg ? -val : val;