1 /*
   2  * Copyright 1996-2009 Sun Microsystems, Inc.  All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 /**
  29  * The {@code Short} class wraps a value of primitive type {@code
  30  * short} in an object.  An object of type {@code Short} contains a
  31  * single field whose type is {@code short}.
  32  *
  33  * <p>In addition, this class provides several methods for converting
  34  * a {@code short} to a {@code String} and a {@code String} to a
  35  * {@code short}, as well as other constants and methods useful when
  36  * dealing with a {@code short}.
  37  *
  38  * @author  Nakul Saraiya
  39  * @author  Joseph D. Darcy
  40  * @see     java.lang.Number
  41  * @since   JDK1.1
  42  */
  43 public final class Short extends Number implements Comparable<Short> {
  44 
  45     /**
  46      * A constant holding the minimum value a {@code short} can
  47      * have, -2<sup>15</sup>.
  48      */
  49     public static final short   MIN_VALUE = -32768;
  50 
  51     /**
  52      * A constant holding the maximum value a {@code short} can
  53      * have, 2<sup>15</sup>-1.
  54      */
  55     public static final short   MAX_VALUE = 32767;
  56 
  57     /**
  58      * The {@code Class} instance representing the primitive type
  59      * {@code short}.
  60      */
  61     public static final Class<Short>    TYPE = (Class<Short>) Class.getPrimitiveClass("short");
  62 
  63     /**
  64      * Returns a new {@code String} object representing the
  65      * specified {@code short}. The radix is assumed to be 10.
  66      *
  67      * @param s the {@code short} to be converted
  68      * @return the string representation of the specified {@code short}
  69      * @see java.lang.Integer#toString(int)
  70      */
  71     public static String toString(short s) {
  72         return Integer.toString((int)s, 10);
  73     }
  74 
  75     /**
  76      * Parses the string argument as a signed {@code short} in the
  77      * radix specified by the second argument. The characters in the
  78      * string must all be digits, of the specified radix (as
  79      * determined by whether {@link java.lang.Character#digit(char,
  80      * int)} returns a nonnegative value) except that the first
  81      * character may be an ASCII minus sign {@code '-'}
  82      * (<code>'&#92;u002D'</code>) to indicate a negative value or an
  83      * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
  84      * indicate a positive value.  The resulting {@code short} value
  85      * is returned.
  86      *
  87      * <p>An exception of type {@code NumberFormatException} is
  88      * thrown if any of the following situations occurs:
  89      * <ul>
  90      * <li> The first argument is {@code null} or is a string of
  91      * length zero.
  92      *
  93      * <li> The radix is either smaller than {@link
  94      * java.lang.Character#MIN_RADIX} or larger than {@link
  95      * java.lang.Character#MAX_RADIX}.
  96      *
  97      * <li> Any character of the string is not a digit of the
  98      * specified radix, except that the first character may be a minus
  99      * sign {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
 100      * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
 101      * string is longer than length 1.
 102      *
 103      * <li> The value represented by the string is not a value of type
 104      * {@code short}.
 105      * </ul>
 106      *
 107      * @param s         the {@code String} containing the
 108      *                  {@code short} representation to be parsed
 109      * @param radix     the radix to be used while parsing {@code s}
 110      * @return          the {@code short} represented by the string
 111      *                  argument in the specified radix.
 112      * @throws          NumberFormatException If the {@code String}
 113      *                  does not contain a parsable {@code short}.
 114      */
 115     public static short parseShort(String s, int radix)
 116         throws NumberFormatException {
 117         int i = Integer.parseInt(s, radix);
 118         if (i < MIN_VALUE || i > MAX_VALUE)
 119             throw new NumberFormatException(
 120                 "Value out of range. Value:\"" + s + "\" Radix:" + radix);
 121         return (short)i;
 122     }
 123 
 124     /**
 125      * Parses the string argument as a signed decimal {@code
 126      * short}. The characters in the string must all be decimal
 127      * digits, except that the first character may be an ASCII minus
 128      * sign {@code '-'} (<code>'&#92;u002D'</code>) to indicate a
 129      * negative value or an ASCII plus sign {@code '+'}
 130      * (<code>'&#92;u002B'</code>) to indicate a positive value.  The
 131      * resulting {@code short} value is returned, exactly as if the
 132      * argument and the radix 10 were given as arguments to the {@link
 133      * #parseShort(java.lang.String, int)} method.
 134      *
 135      * @param s a {@code String} containing the {@code short}
 136      *          representation to be parsed
 137      * @return  the {@code short} value represented by the
 138      *          argument in decimal.
 139      * @throws  NumberFormatException If the string does not
 140      *          contain a parsable {@code short}.
 141      */
 142     public static short parseShort(String s) throws NumberFormatException {
 143         return parseShort(s, 10);
 144     }
 145 
 146     /**
 147      * Returns a {@code Short} object holding the value
 148      * extracted from the specified {@code String} when parsed
 149      * with the radix given by the second argument. The first argument
 150      * is interpreted as representing a signed {@code short} in
 151      * the radix specified by the second argument, exactly as if the
 152      * argument were given to the {@link #parseShort(java.lang.String,
 153      * int)} method. The result is a {@code Short} object that
 154      * represents the {@code short} value specified by the string.
 155      *
 156      * <p>In other words, this method returns a {@code Short} object
 157      * equal to the value of:
 158      *
 159      * <blockquote>
 160      *  {@code new Short(Short.parseShort(s, radix))}
 161      * </blockquote>
 162      *
 163      * @param s         the string to be parsed
 164      * @param radix     the radix to be used in interpreting {@code s}
 165      * @return          a {@code Short} object holding the value
 166      *                  represented by the string argument in the
 167      *                  specified radix.
 168      * @throws          NumberFormatException If the {@code String} does
 169      *                  not contain a parsable {@code short}.
 170      */
 171     public static Short valueOf(String s, int radix)
 172         throws NumberFormatException {
 173         return valueOf(parseShort(s, radix));
 174     }
 175 
 176     /**
 177      * Returns a {@code Short} object holding the
 178      * value given by the specified {@code String}. The argument
 179      * is interpreted as representing a signed decimal
 180      * {@code short}, exactly as if the argument were given to
 181      * the {@link #parseShort(java.lang.String)} method. The result is
 182      * a {@code Short} object that represents the
 183      * {@code short} value specified by the string.
 184      *
 185      * <p>In other words, this method returns a {@code Short} object
 186      * equal to the value of:
 187      *
 188      * <blockquote>
 189      *  {@code new Short(Short.parseShort(s))}
 190      * </blockquote>
 191      *
 192      * @param s the string to be parsed
 193      * @return  a {@code Short} object holding the value
 194      *          represented by the string argument
 195      * @throws  NumberFormatException If the {@code String} does
 196      *          not contain a parsable {@code short}.
 197      */
 198     public static Short valueOf(String s) throws NumberFormatException {
 199         return valueOf(s, 10);
 200     }
 201 
 202     private static class ShortCache {
 203         private ShortCache(){}
 204 
 205         static final Short cache[] = new Short[-(-128) + 127 + 1];
 206 
 207         static {
 208             for(int i = 0; i < cache.length; i++)
 209                 cache[i] = new Short((short)(i - 128));
 210         }
 211     }
 212 
 213     /**
 214      * Returns a {@code Short} instance representing the specified
 215      * {@code short} value.
 216      * If a new {@code Short} instance is not required, this method
 217      * should generally be used in preference to the constructor
 218      * {@link #Short(short)}, as this method is likely to yield
 219      * significantly better space and time performance by caching
 220      * frequently requested values.
 221      *
 222      * This method will always cache values in the range -128 to 127,
 223      * inclusive, and may cache other values outside of this range.
 224      *
 225      * @param  s a short value.
 226      * @return a {@code Short} instance representing {@code s}.
 227      * @since  1.5
 228      */
 229     public static Short valueOf(short s) {
 230         final int offset = 128;
 231         int sAsInt = s;
 232         if (sAsInt >= -128 && sAsInt <= 127) { // must cache
 233             return ShortCache.cache[sAsInt + offset];
 234         }
 235         return new Short(s);
 236     }
 237 
 238     /**
 239      * Decodes a {@code String} into a {@code Short}.
 240      * Accepts decimal, hexadecimal, and octal numbers given by
 241      * the following grammar:
 242      *
 243      * <blockquote>
 244      * <dl>
 245      * <dt><i>DecodableString:</i>
 246      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
 247      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
 248      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
 249      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
 250      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
 251      * <p>
 252      * <dt><i>Sign:</i>
 253      * <dd>{@code -}
 254      * <dd>{@code +}
 255      * </dl>
 256      * </blockquote>
 257      *
 258      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
 259      * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a>
 260      * of the <a href="http://java.sun.com/docs/books/jls/html/">Java
 261      * Language Specification</a>.
 262      *
 263      * <p>The sequence of characters following an optional
 264      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
 265      * "{@code #}", or leading zero) is parsed as by the {@code
 266      * Short.parseShort} method with the indicated radix (10, 16, or
 267      * 8).  This sequence of characters must represent a positive
 268      * value or a {@link NumberFormatException} will be thrown.  The
 269      * result is negated if first character of the specified {@code
 270      * String} is the minus sign.  No whitespace characters are
 271      * permitted in the {@code String}.
 272      *
 273      * @param     nm the {@code String} to decode.
 274      * @return    a {@code Short} object holding the {@code short}
 275      *            value represented by {@code nm}
 276      * @throws    NumberFormatException  if the {@code String} does not
 277      *            contain a parsable {@code short}.
 278      * @see java.lang.Short#parseShort(java.lang.String, int)
 279      */
 280     public static Short decode(String nm) throws NumberFormatException {
 281         int i = Integer.decode(nm);
 282         if (i < MIN_VALUE || i > MAX_VALUE)
 283             throw new NumberFormatException(
 284                     "Value " + i + " out of range from input " + nm);
 285         return valueOf((short)i);
 286     }
 287 
 288     /**
 289      * The value of the {@code Short}.
 290      *
 291      * @serial
 292      */
 293     private final short value;
 294 
 295     /**
 296      * Constructs a newly allocated {@code Short} object that
 297      * represents the specified {@code short} value.
 298      *
 299      * @param value     the value to be represented by the
 300      *                  {@code Short}.
 301      */
 302     public Short(short value) {
 303         this.value = value;
 304     }
 305 
 306     /**
 307      * Constructs a newly allocated {@code Short} object that
 308      * represents the {@code short} value indicated by the
 309      * {@code String} parameter. The string is converted to a
 310      * {@code short} value in exactly the manner used by the
 311      * {@code parseShort} method for radix 10.
 312      *
 313      * @param s the {@code String} to be converted to a
 314      *          {@code Short}
 315      * @throws  NumberFormatException If the {@code String}
 316      *          does not contain a parsable {@code short}.
 317      * @see     java.lang.Short#parseShort(java.lang.String, int)
 318      */
 319     public Short(String s) throws NumberFormatException {
 320         this.value = parseShort(s, 10);
 321     }
 322 
 323     /**
 324      * Returns the value of this {@code Short} as a
 325      * {@code byte}.
 326      */
 327     public byte byteValue() {
 328         return (byte)value;
 329     }
 330 
 331     /**
 332      * Returns the value of this {@code Short} as a
 333      * {@code short}.
 334      */
 335     public short shortValue() {
 336         return value;
 337     }
 338 
 339     /**
 340      * Returns the value of this {@code Short} as an
 341      * {@code int}.
 342      */
 343     public int intValue() {
 344         return (int)value;
 345     }
 346 
 347     /**
 348      * Returns the value of this {@code Short} as a
 349      * {@code long}.
 350      */
 351     public long longValue() {
 352         return (long)value;
 353     }
 354 
 355     /**
 356      * Returns the value of this {@code Short} as a
 357      * {@code float}.
 358      */
 359     public float floatValue() {
 360         return (float)value;
 361     }
 362 
 363     /**
 364      * Returns the value of this {@code Short} as a
 365      * {@code double}.
 366      */
 367     public double doubleValue() {
 368         return (double)value;
 369     }
 370 
 371     /**
 372      * Returns a {@code String} object representing this
 373      * {@code Short}'s value.  The value is converted to signed
 374      * decimal representation and returned as a string, exactly as if
 375      * the {@code short} value were given as an argument to the
 376      * {@link java.lang.Short#toString(short)} method.
 377      *
 378      * @return  a string representation of the value of this object in
 379      *          base&nbsp;10.
 380      */
 381     public String toString() {
 382         return Integer.toString((int)value);
 383     }
 384 
 385     /**
 386      * Returns a hash code for this {@code Short}; equal to the result
 387      * of invoking {@code intValue()}.
 388      *
 389      * @return a hash code value for this {@code Short}
 390      */
 391     public int hashCode() {
 392         return (int)value;
 393     }
 394 
 395     /**
 396      * Compares this object to the specified object.  The result is
 397      * {@code true} if and only if the argument is not
 398      * {@code null} and is a {@code Short} object that
 399      * contains the same {@code short} value as this object.
 400      *
 401      * @param obj       the object to compare with
 402      * @return          {@code true} if the objects are the same;
 403      *                  {@code false} otherwise.
 404      */
 405     public boolean equals(Object obj) {
 406         if (obj instanceof Short) {
 407             return value == ((Short)obj).shortValue();
 408         }
 409         return false;
 410     }
 411 
 412     /**
 413      * Compares two {@code Short} objects numerically.
 414      *
 415      * @param   anotherShort   the {@code Short} to be compared.
 416      * @return  the value {@code 0} if this {@code Short} is
 417      *          equal to the argument {@code Short}; a value less than
 418      *          {@code 0} if this {@code Short} is numerically less
 419      *          than the argument {@code Short}; and a value greater than
 420      *           {@code 0} if this {@code Short} is numerically
 421      *           greater than the argument {@code Short} (signed
 422      *           comparison).
 423      * @since   1.2
 424      */
 425     public int compareTo(Short anotherShort) {
 426         return compare(this.value, anotherShort.value);
 427     }
 428 
 429     /**
 430      * Compares two {@code short} values numerically.
 431      * The value returned is identical to what would be returned by:
 432      * <pre>
 433      *    Short.valueOf(x).compareTo(Short.valueOf(y))
 434      * </pre>
 435      *
 436      * @param  x the first {@code short} to compare
 437      * @param  y the second {@code short} to compare
 438      * @return the value {@code 0} if {@code x == y};
 439      *         a value less than {@code 0} if {@code x < y}; and
 440      *         a value greater than {@code 0} if {@code x > y}
 441      * @since 1.7
 442      */
 443     public static int compare(short x, short y) {
 444         return x - y;
 445     }
 446 
 447     /**
 448      * The number of bits used to represent a {@code short} value in two's
 449      * complement binary form.
 450      * @since 1.5
 451      */
 452     public static final int SIZE = 16;
 453 
 454     /**
 455      * Returns the value obtained by reversing the order of the bytes in the
 456      * two's complement representation of the specified {@code short} value.
 457      *
 458      * @return the value obtained by reversing (or, equivalently, swapping)
 459      *     the bytes in the specified {@code short} value.
 460      * @since 1.5
 461      */
 462     public static short reverseBytes(short i) {
 463         return (short) (((i & 0xFF00) >> 8) | (i << 8));
 464     }
 465 
 466 
 467     /**
 468      * Converts the argument to an {@code int} by an unsigned
 469      * conversion.  In an unsigned conversion to an {@code int}, the
 470      * high-order 16 bits of the {@code int} are zero and the
 471      * low-order 16 bits are equal to the bits of the {@code short} argument.
 472      *
 473      * @return the argument converted to {@code int} by an unsigned
 474      *         conversion
 475      * @param  x the value to convert to an unsigned {@code int}
 476      * @since 1.7
 477      */
 478     public static int toUnsignedInt(short x) {
 479         return ((int) x) & 0xffff;
 480     }
 481 
 482     /**
 483      * Converts the argument to a {@code long} by an unsigned
 484      * conversion.  In an unsigned conversion to a {@code long}, the
 485      * high-order 48 bits of the {@code long} are zero and the
 486      * low-order 16 bits are equal to the bits of the {@code short} argument.
 487      *
 488      * @return the argument converted to {@code long} by an unsigned
 489      *         conversion
 490      * @param  x the value to convert to an unsigned {@code long}
 491      * @since 1.7
 492      */
 493     public static long toUnsignedLong(short x) {
 494         return ((long) x) & 0xffffL;
 495     }
 496 
 497     /** use serialVersionUID from JDK 1.1. for interoperability */
 498     private static final long serialVersionUID = 7515723908773894738L;
 499 }