1 /*
   2  * Copyright (c) 1996, 2011, Oracle and/or its affiliates. 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * 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 as defined in section 3.10.1 of
 260      * <cite>The Java&trade; Language Specification</cite>,
 261      * except that underscores are not accepted between digits.
 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 {@code byte} after
 325      * a narrowing primitive conversion.
 326      * @jls 5.1.3 Narrowing Primitive Conversions
 327      */
 328     public byte byteValue() {
 329         return (byte)value;
 330     }
 331 
 332     /**
 333      * Returns the value of this {@code Short} as a
 334      * {@code short}.
 335      */
 336     public short shortValue() {
 337         return value;
 338     }
 339 
 340     /**
 341      * Returns the value of this {@code Short} as an {@code int} after
 342      * a widening primitive conversion.
 343      * @jls 5.1.2 Widening Primitive Conversions
 344      */
 345     public int intValue() {
 346         return (int)value;
 347     }
 348 
 349     /**
 350      * Returns the value of this {@code Short} as a {@code long} after
 351      * a widening primitive conversion.
 352      * @jls 5.1.2 Widening Primitive Conversions
 353      */
 354     public long longValue() {
 355         return (long)value;
 356     }
 357 
 358     /**
 359      * Returns the value of this {@code Short} as a {@code float}
 360      * after a widening primitive conversion.
 361      * @jls 5.1.2 Widening Primitive Conversions
 362      */
 363     public float floatValue() {
 364         return (float)value;
 365     }
 366 
 367     /**
 368      * Returns the value of this {@code Short} as a {@code double}
 369      * after a widening primitive conversion.
 370      * @jls 5.1.2 Widening Primitive Conversions
 371      */
 372     public double doubleValue() {
 373         return (double)value;
 374     }
 375 
 376     /**
 377      * Returns a {@code String} object representing this
 378      * {@code Short}'s value.  The value is converted to signed
 379      * decimal representation and returned as a string, exactly as if
 380      * the {@code short} value were given as an argument to the
 381      * {@link java.lang.Short#toString(short)} method.
 382      *
 383      * @return  a string representation of the value of this object in
 384      *          base&nbsp;10.
 385      */
 386     public String toString() {
 387         return Integer.toString((int)value);
 388     }
 389 
 390     /**
 391      * Returns a hash code for this {@code Short}; equal to the result
 392      * of invoking {@code intValue()}.
 393      *
 394      * @return a hash code value for this {@code Short}
 395      */
 396     public int hashCode() {
 397         return (int)value;
 398     }
 399 
 400     /**
 401      * Compares this object to the specified object.  The result is
 402      * {@code true} if and only if the argument is not
 403      * {@code null} and is a {@code Short} object that
 404      * contains the same {@code short} value as this object.
 405      *
 406      * @param obj       the object to compare with
 407      * @return          {@code true} if the objects are the same;
 408      *                  {@code false} otherwise.
 409      */
 410     public boolean equals(Object obj) {
 411         if (obj instanceof Short) {
 412             return value == ((Short)obj).shortValue();
 413         }
 414         return false;
 415     }
 416 
 417     /**
 418      * Compares two {@code Short} objects numerically.
 419      *
 420      * @param   anotherShort   the {@code Short} to be compared.
 421      * @return  the value {@code 0} if this {@code Short} is
 422      *          equal to the argument {@code Short}; a value less than
 423      *          {@code 0} if this {@code Short} is numerically less
 424      *          than the argument {@code Short}; and a value greater than
 425      *           {@code 0} if this {@code Short} is numerically
 426      *           greater than the argument {@code Short} (signed
 427      *           comparison).
 428      * @since   1.2
 429      */
 430     public int compareTo(Short anotherShort) {
 431         return compare(this.value, anotherShort.value);
 432     }
 433 
 434     /**
 435      * Compares two {@code short} values numerically.
 436      * The value returned is identical to what would be returned by:
 437      * <pre>
 438      *    Short.valueOf(x).compareTo(Short.valueOf(y))
 439      * </pre>
 440      *
 441      * @param  x the first {@code short} to compare
 442      * @param  y the second {@code short} to compare
 443      * @return the value {@code 0} if {@code x == y};
 444      *         a value less than {@code 0} if {@code x < y}; and
 445      *         a value greater than {@code 0} if {@code x > y}
 446      * @since 1.7
 447      */
 448     public static int compare(short x, short y) {
 449         return x - y;
 450     }
 451 
 452     /**
 453      * The number of bits used to represent a {@code short} value in two's
 454      * complement binary form.
 455      * @since 1.5
 456      */
 457     public static final int SIZE = 16;
 458 
 459     /**
 460      * Returns the value obtained by reversing the order of the bytes in the
 461      * two's complement representation of the specified {@code short} value.
 462      *
 463      * @return the value obtained by reversing (or, equivalently, swapping)
 464      *     the bytes in the specified {@code short} value.
 465      * @since 1.5
 466      */
 467     public static short reverseBytes(short i) {
 468         return (short) (((i & 0xFF00) >> 8) | (i << 8));
 469     }
 470 
 471     /** use serialVersionUID from JDK 1.1. for interoperability */
 472     private static final long serialVersionUID = 7515723908773894738L;
 473 }