• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 /**
30  * The {@code Short} class wraps a value of primitive type {@code
31  * short} in an object.  An object of type {@code Short} contains a
32  * single field whose type is {@code short}.
33  *
34  * <p>In addition, this class provides several methods for converting
35  * a {@code short} to a {@code String} and a {@code String} to a
36  * {@code short}, as well as other constants and methods useful when
37  * dealing with a {@code short}.
38  *
39  * @author  Nakul Saraiya
40  * @author  Joseph D. Darcy
41  * @see     java.lang.Number
42  * @since   JDK1.1
43  */
44 public final class Short extends Number implements Comparable<Short> {
45 
46     /**
47      * A constant holding the minimum value a {@code short} can
48      * have, -2<sup>15</sup>.
49      */
50     public static final short   MIN_VALUE = -32768;
51 
52     /**
53      * A constant holding the maximum value a {@code short} can
54      * have, 2<sup>15</sup>-1.
55      */
56     public static final short   MAX_VALUE = 32767;
57 
58     /**
59      * The {@code Class} instance representing the primitive type
60      * {@code short}.
61      */
62     public static final Class<Short>    TYPE = (Class<Short>) short[].class.getComponentType();
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      */
toString(short s)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>'&#92;u002D'</code>) to indicate a negative value or an
84      * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) 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>'&#92;u002D'</code>) or plus sign
101      * {@code '+'} (<code>'&#92;u002B'</code>) 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      */
parseShort(String s, int radix)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>'&#92;u002D'</code>) to indicate a
130      * negative value or an ASCII plus sign {@code '+'}
131      * (<code>'&#92;u002B'</code>) 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      */
parseShort(String s)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      */
valueOf(String s, int radix)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      */
valueOf(String s)199     public static Short valueOf(String s) throws NumberFormatException {
200         return valueOf(s, 10);
201     }
202 
203     private static class ShortCache {
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      */
valueOf(short s)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      * <p>
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      */
decode(String nm)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      */
Short(short value)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      */
Short(String s)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
326      * {@code byte}.
327      */
byteValue()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      */
shortValue()336     public short shortValue() {
337         return value;
338     }
339 
340     /**
341      * Returns the value of this {@code Short} as an
342      * {@code int}.
343      */
intValue()344     public int intValue() {
345         return (int)value;
346     }
347 
348     /**
349      * Returns the value of this {@code Short} as a
350      * {@code long}.
351      */
longValue()352     public long longValue() {
353         return (long)value;
354     }
355 
356     /**
357      * Returns the value of this {@code Short} as a
358      * {@code float}.
359      */
floatValue()360     public float floatValue() {
361         return (float)value;
362     }
363 
364     /**
365      * Returns the value of this {@code Short} as a
366      * {@code double}.
367      */
doubleValue()368     public double doubleValue() {
369         return (double)value;
370     }
371 
372     /**
373      * Returns a {@code String} object representing this
374      * {@code Short}'s value.  The value is converted to signed
375      * decimal representation and returned as a string, exactly as if
376      * the {@code short} value were given as an argument to the
377      * {@link java.lang.Short#toString(short)} method.
378      *
379      * @return  a string representation of the value of this object in
380      *          base&nbsp;10.
381      */
toString()382     public String toString() {
383         return Integer.toString((int)value);
384     }
385 
386     /**
387      * Returns a hash code for this {@code Short}; equal to the result
388      * of invoking {@code intValue()}.
389      *
390      * @return a hash code value for this {@code Short}
391      */
hashCode()392     public int hashCode() {
393         return Short.hashCode(value);
394     }
395 
396     /**
397      * Returns a hash code for a {@code short} value; compatible with
398      * {@code Short.hashCode()}.
399      *
400      * @param value the value to hash
401      * @return a hash code value for a {@code short} value.
402      * @since 1.8
403      */
hashCode(short value)404     public static int hashCode(short value) {
405         return (int)value;
406     }
407 
408     /**
409      * Compares this object to the specified object.  The result is
410      * {@code true} if and only if the argument is not
411      * {@code null} and is a {@code Short} object that
412      * contains the same {@code short} value as this object.
413      *
414      * @param obj       the object to compare with
415      * @return          {@code true} if the objects are the same;
416      *                  {@code false} otherwise.
417      */
equals(Object obj)418     public boolean equals(Object obj) {
419         if (obj instanceof Short) {
420             return value == ((Short)obj).shortValue();
421         }
422         return false;
423     }
424 
425     /**
426      * Compares two {@code Short} objects numerically.
427      *
428      * @param   anotherShort   the {@code Short} to be compared.
429      * @return  the value {@code 0} if this {@code Short} is
430      *          equal to the argument {@code Short}; a value less than
431      *          {@code 0} if this {@code Short} is numerically less
432      *          than the argument {@code Short}; and a value greater than
433      *           {@code 0} if this {@code Short} is numerically
434      *           greater than the argument {@code Short} (signed
435      *           comparison).
436      * @since   1.2
437      */
compareTo(Short anotherShort)438     public int compareTo(Short anotherShort) {
439         return compare(this.value, anotherShort.value);
440     }
441 
442     /**
443      * Compares two {@code short} values numerically.
444      * The value returned is identical to what would be returned by:
445      * <pre>
446      *    Short.valueOf(x).compareTo(Short.valueOf(y))
447      * </pre>
448      *
449      * @param  x the first {@code short} to compare
450      * @param  y the second {@code short} to compare
451      * @return the value {@code 0} if {@code x == y};
452      *         a value less than {@code 0} if {@code x < y}; and
453      *         a value greater than {@code 0} if {@code x > y}
454      * @since 1.7
455      */
compare(short x, short y)456     public static int compare(short x, short y) {
457         return x - y;
458     }
459 
460     /**
461      * The number of bits used to represent a {@code short} value in two's
462      * complement binary form.
463      * @since 1.5
464      */
465     public static final int SIZE = 16;
466 
467     /**
468      * The number of bytes used to represent a {@code short} value in two's
469      * complement binary form.
470      *
471      * @since 1.8
472      */
473     public static final int BYTES = SIZE / Byte.SIZE;
474 
475     /**
476      * Returns the value obtained by reversing the order of the bytes in the
477      * two's complement representation of the specified {@code short} value.
478      *
479      * @return the value obtained by reversing (or, equivalently, swapping)
480      *     the bytes in the specified {@code short} value.
481      * @since 1.5
482      */
reverseBytes(short i)483     public static short reverseBytes(short i) {
484         return (short) (((i & 0xFF00) >> 8) | (i << 8));
485     }
486 
487     /** use serialVersionUID from JDK 1.1. for interoperability */
488     private static final long serialVersionUID = 7515723908773894738L;
489 }
490