View Javadoc
1   /*
2    * Copyright (c) 1996, 2013, 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      @SuppressWarnings("unchecked")
62      public static final Class<Short>    TYPE = (Class<Short>) Class.getPrimitiveClass("short");
63  
64      /**
65       * Returns a new {@code String} object representing the
66       * specified {@code short}. The radix is assumed to be 10.
67       *
68       * @param s the {@code short} to be converted
69       * @return the string representation of the specified {@code short}
70       * @see java.lang.Integer#toString(int)
71       */
72      public static String toString(short s) {
73          return Integer.toString((int)s, 10);
74      }
75  
76      /**
77       * Parses the string argument as a signed {@code short} in the
78       * radix specified by the second argument. The characters in the
79       * string must all be digits, of the specified radix (as
80       * determined by whether {@link java.lang.Character#digit(char,
81       * int)} returns a nonnegative value) except that the first
82       * character may be an ASCII minus sign {@code '-'}
83       * ({@code '\u005Cu002D'}) to indicate a negative value or an
84       * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
85       * indicate a positive value.  The resulting {@code short} value
86       * is returned.
87       *
88       * <p>An exception of type {@code NumberFormatException} is
89       * thrown if any of the following situations occurs:
90       * <ul>
91       * <li> The first argument is {@code null} or is a string of
92       * length zero.
93       *
94       * <li> The radix is either smaller than {@link
95       * java.lang.Character#MIN_RADIX} or larger than {@link
96       * java.lang.Character#MAX_RADIX}.
97       *
98       * <li> Any character of the string is not a digit of the
99       * specified radix, except that the first character may be a minus
100      * sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
101      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
102      * string is longer than length 1.
103      *
104      * <li> The value represented by the string is not a value of type
105      * {@code short}.
106      * </ul>
107      *
108      * @param s         the {@code String} containing the
109      *                  {@code short} representation to be parsed
110      * @param radix     the radix to be used while parsing {@code s}
111      * @return          the {@code short} represented by the string
112      *                  argument in the specified radix.
113      * @throws          NumberFormatException If the {@code String}
114      *                  does not contain a parsable {@code short}.
115      */
116     public static short parseShort(String s, int radix)
117         throws NumberFormatException {
118         int i = Integer.parseInt(s, radix);
119         if (i < MIN_VALUE || i > MAX_VALUE)
120             throw new NumberFormatException(
121                 "Value out of range. Value:\"" + s + "\" Radix:" + radix);
122         return (short)i;
123     }
124 
125     /**
126      * Parses the string argument as a signed decimal {@code
127      * short}. The characters in the string must all be decimal
128      * digits, except that the first character may be an ASCII minus
129      * sign {@code '-'} ({@code '\u005Cu002D'}) to indicate a
130      * negative value or an ASCII plus sign {@code '+'}
131      * ({@code '\u005Cu002B'}) to indicate a positive value.  The
132      * resulting {@code short} value is returned, exactly as if the
133      * argument and the radix 10 were given as arguments to the {@link
134      * #parseShort(java.lang.String, int)} method.
135      *
136      * @param s a {@code String} containing the {@code short}
137      *          representation to be parsed
138      * @return  the {@code short} value represented by the
139      *          argument in decimal.
140      * @throws  NumberFormatException If the string does not
141      *          contain a parsable {@code short}.
142      */
143     public static short parseShort(String s) throws NumberFormatException {
144         return parseShort(s, 10);
145     }
146 
147     /**
148      * Returns a {@code Short} object holding the value
149      * extracted from the specified {@code String} when parsed
150      * with the radix given by the second argument. The first argument
151      * is interpreted as representing a signed {@code short} in
152      * the radix specified by the second argument, exactly as if the
153      * argument were given to the {@link #parseShort(java.lang.String,
154      * int)} method. The result is a {@code Short} object that
155      * represents the {@code short} value specified by the string.
156      *
157      * <p>In other words, this method returns a {@code Short} object
158      * equal to the value of:
159      *
160      * <blockquote>
161      *  {@code new Short(Short.parseShort(s, radix))}
162      * </blockquote>
163      *
164      * @param s         the string to be parsed
165      * @param radix     the radix to be used in interpreting {@code s}
166      * @return          a {@code Short} object holding the value
167      *                  represented by the string argument in the
168      *                  specified radix.
169      * @throws          NumberFormatException If the {@code String} does
170      *                  not contain a parsable {@code short}.
171      */
172     public static Short valueOf(String s, int radix)
173         throws NumberFormatException {
174         return valueOf(parseShort(s, radix));
175     }
176 
177     /**
178      * Returns a {@code Short} object holding the
179      * value given by the specified {@code String}. The argument
180      * is interpreted as representing a signed decimal
181      * {@code short}, exactly as if the argument were given to
182      * the {@link #parseShort(java.lang.String)} method. The result is
183      * a {@code Short} object that represents the
184      * {@code short} value specified by the string.
185      *
186      * <p>In other words, this method returns a {@code Short} object
187      * equal to the value of:
188      *
189      * <blockquote>
190      *  {@code new Short(Short.parseShort(s))}
191      * </blockquote>
192      *
193      * @param s the string to be parsed
194      * @return  a {@code Short} object holding the value
195      *          represented by the string argument
196      * @throws  NumberFormatException If the {@code String} does
197      *          not contain a parsable {@code short}.
198      */
199     public static Short valueOf(String s) throws NumberFormatException {
200         return valueOf(s, 10);
201     }
202 
203     private static class ShortCache {
204         private ShortCache(){}
205 
206         static final Short cache[] = new Short[-(-128) + 127 + 1];
207 
208         static {
209             for(int i = 0; i < cache.length; i++)
210                 cache[i] = new Short((short)(i - 128));
211         }
212     }
213 
214     /**
215      * Returns a {@code Short} instance representing the specified
216      * {@code short} value.
217      * If a new {@code Short} instance is not required, this method
218      * should generally be used in preference to the constructor
219      * {@link #Short(short)}, as this method is likely to yield
220      * significantly better space and time performance by caching
221      * frequently requested values.
222      *
223      * This method will always cache values in the range -128 to 127,
224      * inclusive, and may cache other values outside of this range.
225      *
226      * @param  s a short value.
227      * @return a {@code Short} instance representing {@code s}.
228      * @since  1.5
229      */
230     public static Short valueOf(short s) {
231         final int offset = 128;
232         int sAsInt = s;
233         if (sAsInt >= -128 && sAsInt <= 127) { // must cache
234             return ShortCache.cache[sAsInt + offset];
235         }
236         return new Short(s);
237     }
238 
239     /**
240      * Decodes a {@code String} into a {@code Short}.
241      * Accepts decimal, hexadecimal, and octal numbers given by
242      * the following grammar:
243      *
244      * <blockquote>
245      * <dl>
246      * <dt><i>DecodableString:</i>
247      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
248      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
249      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
250      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
251      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
252      *
253      * <dt><i>Sign:</i>
254      * <dd>{@code -}
255      * <dd>{@code +}
256      * </dl>
257      * </blockquote>
258      *
259      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
260      * are as defined in section 3.10.1 of
261      * <cite>The Java&trade; Language Specification</cite>,
262      * except that underscores are not accepted between digits.
263      *
264      * <p>The sequence of characters following an optional
265      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
266      * "{@code #}", or leading zero) is parsed as by the {@code
267      * Short.parseShort} method with the indicated radix (10, 16, or
268      * 8).  This sequence of characters must represent a positive
269      * value or a {@link NumberFormatException} will be thrown.  The
270      * result is negated if first character of the specified {@code
271      * String} is the minus sign.  No whitespace characters are
272      * permitted in the {@code String}.
273      *
274      * @param     nm the {@code String} to decode.
275      * @return    a {@code Short} object holding the {@code short}
276      *            value represented by {@code nm}
277      * @throws    NumberFormatException  if the {@code String} does not
278      *            contain a parsable {@code short}.
279      * @see java.lang.Short#parseShort(java.lang.String, int)
280      */
281     public static Short decode(String nm) throws NumberFormatException {
282         int i = Integer.decode(nm);
283         if (i < MIN_VALUE || i > MAX_VALUE)
284             throw new NumberFormatException(
285                     "Value " + i + " out of range from input " + nm);
286         return valueOf((short)i);
287     }
288 
289     /**
290      * The value of the {@code Short}.
291      *
292      * @serial
293      */
294     private final short value;
295 
296     /**
297      * Constructs a newly allocated {@code Short} object that
298      * represents the specified {@code short} value.
299      *
300      * @param value     the value to be represented by the
301      *                  {@code Short}.
302      */
303     public Short(short value) {
304         this.value = value;
305     }
306 
307     /**
308      * Constructs a newly allocated {@code Short} object that
309      * represents the {@code short} value indicated by the
310      * {@code String} parameter. The string is converted to a
311      * {@code short} value in exactly the manner used by the
312      * {@code parseShort} method for radix 10.
313      *
314      * @param s the {@code String} to be converted to a
315      *          {@code Short}
316      * @throws  NumberFormatException If the {@code String}
317      *          does not contain a parsable {@code short}.
318      * @see     java.lang.Short#parseShort(java.lang.String, int)
319      */
320     public Short(String s) throws NumberFormatException {
321         this.value = parseShort(s, 10);
322     }
323 
324     /**
325      * Returns the value of this {@code Short} as a {@code byte} after
326      * a narrowing primitive conversion.
327      * @jls 5.1.3 Narrowing Primitive Conversions
328      */
329     public byte byteValue() {
330         return (byte)value;
331     }
332 
333     /**
334      * Returns the value of this {@code Short} as a
335      * {@code short}.
336      */
337     public short shortValue() {
338         return value;
339     }
340 
341     /**
342      * Returns the value of this {@code Short} as an {@code int} after
343      * a widening primitive conversion.
344      * @jls 5.1.2 Widening Primitive Conversions
345      */
346     public int intValue() {
347         return (int)value;
348     }
349 
350     /**
351      * Returns the value of this {@code Short} as a {@code long} after
352      * a widening primitive conversion.
353      * @jls 5.1.2 Widening Primitive Conversions
354      */
355     public long longValue() {
356         return (long)value;
357     }
358 
359     /**
360      * Returns the value of this {@code Short} as a {@code float}
361      * after a widening primitive conversion.
362      * @jls 5.1.2 Widening Primitive Conversions
363      */
364     public float floatValue() {
365         return (float)value;
366     }
367 
368     /**
369      * Returns the value of this {@code Short} as a {@code double}
370      * after a widening primitive conversion.
371      * @jls 5.1.2 Widening Primitive Conversions
372      */
373     public double doubleValue() {
374         return (double)value;
375     }
376 
377     /**
378      * Returns a {@code String} object representing this
379      * {@code Short}'s value.  The value is converted to signed
380      * decimal representation and returned as a string, exactly as if
381      * the {@code short} value were given as an argument to the
382      * {@link java.lang.Short#toString(short)} method.
383      *
384      * @return  a string representation of the value of this object in
385      *          base&nbsp;10.
386      */
387     public String toString() {
388         return Integer.toString((int)value);
389     }
390 
391     /**
392      * Returns a hash code for this {@code Short}; equal to the result
393      * of invoking {@code intValue()}.
394      *
395      * @return a hash code value for this {@code Short}
396      */
397     @Override
398     public int hashCode() {
399         return Short.hashCode(value);
400     }
401 
402     /**
403      * Returns a hash code for a {@code short} value; compatible with
404      * {@code Short.hashCode()}.
405      *
406      * @param value the value to hash
407      * @return a hash code value for a {@code short} value.
408      * @since 1.8
409      */
410     public static int hashCode(short value) {
411         return (int)value;
412     }
413 
414     /**
415      * Compares this object to the specified object.  The result is
416      * {@code true} if and only if the argument is not
417      * {@code null} and is a {@code Short} object that
418      * contains the same {@code short} value as this object.
419      *
420      * @param obj       the object to compare with
421      * @return          {@code true} if the objects are the same;
422      *                  {@code false} otherwise.
423      */
424     public boolean equals(Object obj) {
425         if (obj instanceof Short) {
426             return value == ((Short)obj).shortValue();
427         }
428         return false;
429     }
430 
431     /**
432      * Compares two {@code Short} objects numerically.
433      *
434      * @param   anotherShort   the {@code Short} to be compared.
435      * @return  the value {@code 0} if this {@code Short} is
436      *          equal to the argument {@code Short}; a value less than
437      *          {@code 0} if this {@code Short} is numerically less
438      *          than the argument {@code Short}; and a value greater than
439      *           {@code 0} if this {@code Short} is numerically
440      *           greater than the argument {@code Short} (signed
441      *           comparison).
442      * @since   1.2
443      */
444     public int compareTo(Short anotherShort) {
445         return compare(this.value, anotherShort.value);
446     }
447 
448     /**
449      * Compares two {@code short} values numerically.
450      * The value returned is identical to what would be returned by:
451      * <pre>
452      *    Short.valueOf(x).compareTo(Short.valueOf(y))
453      * </pre>
454      *
455      * @param  x the first {@code short} to compare
456      * @param  y the second {@code short} to compare
457      * @return the value {@code 0} if {@code x == y};
458      *         a value less than {@code 0} if {@code x < y}; and
459      *         a value greater than {@code 0} if {@code x > y}
460      * @since 1.7
461      */
462     public static int compare(short x, short y) {
463         return x - y;
464     }
465 
466     /**
467      * The number of bits used to represent a {@code short} value in two's
468      * complement binary form.
469      * @since 1.5
470      */
471     public static final int SIZE = 16;
472 
473     /**
474      * The number of bytes used to represent a {@code short} value in two's
475      * complement binary form.
476      *
477      * @since 1.8
478      */
479     public static final int BYTES = SIZE / Byte.SIZE;
480 
481     /**
482      * Returns the value obtained by reversing the order of the bytes in the
483      * two's complement representation of the specified {@code short} value.
484      *
485      * @param i the value whose bytes are to be reversed
486      * @return the value obtained by reversing (or, equivalently, swapping)
487      *     the bytes in the specified {@code short} value.
488      * @since 1.5
489      */
490     public static short reverseBytes(short i) {
491         return (short) (((i & 0xFF00) >> 8) | (i << 8));
492     }
493 
494 
495     /**
496      * Converts the argument to an {@code int} by an unsigned
497      * conversion.  In an unsigned conversion to an {@code int}, the
498      * high-order 16 bits of the {@code int} are zero and the
499      * low-order 16 bits are equal to the bits of the {@code short} argument.
500      *
501      * Consequently, zero and positive {@code short} values are mapped
502      * to a numerically equal {@code int} value and negative {@code
503      * short} values are mapped to an {@code int} value equal to the
504      * input plus 2<sup>16</sup>.
505      *
506      * @param  x the value to convert to an unsigned {@code int}
507      * @return the argument converted to {@code int} by an unsigned
508      *         conversion
509      * @since 1.8
510      */
511     public static int toUnsignedInt(short x) {
512         return ((int) x) & 0xffff;
513     }
514 
515     /**
516      * Converts the argument to a {@code long} by an unsigned
517      * conversion.  In an unsigned conversion to a {@code long}, the
518      * high-order 48 bits of the {@code long} are zero and the
519      * low-order 16 bits are equal to the bits of the {@code short} argument.
520      *
521      * Consequently, zero and positive {@code short} values are mapped
522      * to a numerically equal {@code long} value and negative {@code
523      * short} values are mapped to a {@code long} value equal to the
524      * input plus 2<sup>16</sup>.
525      *
526      * @param  x the value to convert to an unsigned {@code long}
527      * @return the argument converted to {@code long} by an unsigned
528      *         conversion
529      * @since 1.8
530      */
531     public static long toUnsignedLong(short x) {
532         return ((long) x) & 0xffffL;
533     }
534 
535     /** use serialVersionUID from JDK 1.1. for interoperability */
536     private static final long serialVersionUID = 7515723908773894738L;
537 }