• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1996, 2020, 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 // Android-removed: CDS is not used on Android.
29 // import jdk.internal.misc.CDS;
30 import jdk.internal.vm.annotation.IntrinsicCandidate;
31 
32 import java.lang.constant.Constable;
33 import java.lang.constant.DynamicConstantDesc;
34 import java.util.Optional;
35 
36 import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;
37 import static java.lang.constant.ConstantDescs.CD_int;
38 import static java.lang.constant.ConstantDescs.CD_short;
39 import static java.lang.constant.ConstantDescs.DEFAULT_NAME;
40 
41 /**
42  * The {@code Short} class wraps a value of primitive type {@code
43  * short} in an object.  An object of type {@code Short} contains a
44  * single field whose type is {@code short}.
45  *
46  * <p>In addition, this class provides several methods for converting
47  * a {@code short} to a {@code String} and a {@code String} to a
48  * {@code short}, as well as other constants and methods useful when
49  * dealing with a {@code short}.
50  *
51  * <!-- Android-removed: paragraph on ValueBased
52  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
53  * class; programmers should treat instances that are
54  * {@linkplain #equals(Object) equal} as interchangeable and should not
55  * use instances for synchronization, or unpredictable behavior may
56  * occur. For example, in a future release, synchronization may fail.
57  * -->
58  *
59  * @author  Nakul Saraiya
60  * @author  Joseph D. Darcy
61  * @see     java.lang.Number
62  * @since   1.1
63  */
64 @jdk.internal.ValueBased
65 public final class Short extends Number implements Comparable<Short>, Constable {
66 
67     /**
68      * A constant holding the minimum value a {@code short} can
69      * have, -2<sup>15</sup>.
70      */
71     public static final short   MIN_VALUE = -32768;
72 
73     /**
74      * A constant holding the maximum value a {@code short} can
75      * have, 2<sup>15</sup>-1.
76      */
77     public static final short   MAX_VALUE = 32767;
78 
79     /**
80      * The {@code Class} instance representing the primitive type
81      * {@code short}.
82      */
83     @SuppressWarnings("unchecked")
84     public static final Class<Short>    TYPE = (Class<Short>) Class.getPrimitiveClass("short");
85 
86     /**
87      * Returns a new {@code String} object representing the
88      * specified {@code short}. The radix is assumed to be 10.
89      *
90      * @param s the {@code short} to be converted
91      * @return the string representation of the specified {@code short}
92      * @see java.lang.Integer#toString(int)
93      */
toString(short s)94     public static String toString(short s) {
95         return Integer.toString((int)s, 10);
96     }
97 
98     /**
99      * Parses the string argument as a signed {@code short} in the
100      * radix specified by the second argument. The characters in the
101      * string must all be digits, of the specified radix (as
102      * determined by whether {@link java.lang.Character#digit(char,
103      * int)} returns a nonnegative value) except that the first
104      * character may be an ASCII minus sign {@code '-'}
105      * ({@code '\u005Cu002D'}) to indicate a negative value or an
106      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
107      * indicate a positive value.  The resulting {@code short} value
108      * is returned.
109      *
110      * <p>An exception of type {@code NumberFormatException} is
111      * thrown if any of the following situations occurs:
112      * <ul>
113      * <li> The first argument is {@code null} or is a string of
114      * length zero.
115      *
116      * <li> The radix is either smaller than {@link
117      * java.lang.Character#MIN_RADIX} or larger than {@link
118      * java.lang.Character#MAX_RADIX}.
119      *
120      * <li> Any character of the string is not a digit of the
121      * specified radix, except that the first character may be a minus
122      * sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
123      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
124      * string is longer than length 1.
125      *
126      * <li> The value represented by the string is not a value of type
127      * {@code short}.
128      * </ul>
129      *
130      * @param s         the {@code String} containing the
131      *                  {@code short} representation to be parsed
132      * @param radix     the radix to be used while parsing {@code s}
133      * @return          the {@code short} represented by the string
134      *                  argument in the specified radix.
135      * @throws          NumberFormatException If the {@code String}
136      *                  does not contain a parsable {@code short}.
137      */
parseShort(String s, int radix)138     public static short parseShort(String s, int radix)
139         throws NumberFormatException {
140         int i = Integer.parseInt(s, radix);
141         if (i < MIN_VALUE || i > MAX_VALUE)
142             throw new NumberFormatException(
143                 "Value out of range. Value:\"" + s + "\" Radix:" + radix);
144         return (short)i;
145     }
146 
147     /**
148      * Parses the string argument as a signed decimal {@code
149      * short}. The characters in the string must all be decimal
150      * digits, except that the first character may be an ASCII minus
151      * sign {@code '-'} ({@code '\u005Cu002D'}) to indicate a
152      * negative value or an ASCII plus sign {@code '+'}
153      * ({@code '\u005Cu002B'}) to indicate a positive value.  The
154      * resulting {@code short} value is returned, exactly as if the
155      * argument and the radix 10 were given as arguments to the {@link
156      * #parseShort(java.lang.String, int)} method.
157      *
158      * @param s a {@code String} containing the {@code short}
159      *          representation to be parsed
160      * @return  the {@code short} value represented by the
161      *          argument in decimal.
162      * @throws  NumberFormatException If the string does not
163      *          contain a parsable {@code short}.
164      */
parseShort(String s)165     public static short parseShort(String s) throws NumberFormatException {
166         return parseShort(s, 10);
167     }
168 
169     /**
170      * Returns a {@code Short} object holding the value
171      * extracted from the specified {@code String} when parsed
172      * with the radix given by the second argument. The first argument
173      * is interpreted as representing a signed {@code short} in
174      * the radix specified by the second argument, exactly as if the
175      * argument were given to the {@link #parseShort(java.lang.String,
176      * int)} method. The result is a {@code Short} object that
177      * represents the {@code short} value specified by the string.
178      *
179      * <p>In other words, this method returns a {@code Short} object
180      * equal to the value of:
181      *
182      * <blockquote>
183      *  {@code new Short(Short.parseShort(s, radix))}
184      * </blockquote>
185      *
186      * @param s         the string to be parsed
187      * @param radix     the radix to be used in interpreting {@code s}
188      * @return          a {@code Short} object holding the value
189      *                  represented by the string argument in the
190      *                  specified radix.
191      * @throws          NumberFormatException If the {@code String} does
192      *                  not contain a parsable {@code short}.
193      */
valueOf(String s, int radix)194     public static Short valueOf(String s, int radix)
195         throws NumberFormatException {
196         return valueOf(parseShort(s, radix));
197     }
198 
199     /**
200      * Returns a {@code Short} object holding the
201      * value given by the specified {@code String}. The argument
202      * is interpreted as representing a signed decimal
203      * {@code short}, exactly as if the argument were given to
204      * the {@link #parseShort(java.lang.String)} method. The result is
205      * a {@code Short} object that represents the
206      * {@code short} value specified by the string.
207      *
208      * <p>In other words, this method returns a {@code Short} object
209      * equal to the value of:
210      *
211      * <blockquote>
212      *  {@code new Short(Short.parseShort(s))}
213      * </blockquote>
214      *
215      * @param s the string to be parsed
216      * @return  a {@code Short} object holding the value
217      *          represented by the string argument
218      * @throws  NumberFormatException If the {@code String} does
219      *          not contain a parsable {@code short}.
220      */
valueOf(String s)221     public static Short valueOf(String s) throws NumberFormatException {
222         return valueOf(s, 10);
223     }
224 
225     /**
226      * Returns an {@link Optional} containing the nominal descriptor for this
227      * instance.
228      *
229      * @return an {@link Optional} describing the {@linkplain Short} instance
230      * @since 15
231      * @hide
232      */
233     @Override
describeConstable()234     public Optional<DynamicConstantDesc<Short>> describeConstable() {
235         return Optional.of(DynamicConstantDesc.ofNamed(BSM_EXPLICIT_CAST, DEFAULT_NAME, CD_short, intValue()));
236     }
237 
238     private static class ShortCache {
ShortCache()239         private ShortCache() {}
240 
241         static final Short[] cache;
242         static Short[] archivedCache;
243 
244         static {
245             int size = -(-128) + 127 + 1;
246 
247             // Load and use the archived cache if it exists
248             // Android-removed: CDS is not used on Android.
249             // CDS.initializeFromArchive(ShortCache.class);
250             if (archivedCache == null || archivedCache.length != size) {
251                 Short[] c = new Short[size];
252                 short value = -128;
253                 for(int i = 0; i < size; i++) {
254                     c[i] = new Short(value++);
255                 }
256                 archivedCache = c;
257             }
258             cache = archivedCache;
259         }
260     }
261 
262     /**
263      * Returns a {@code Short} instance representing the specified
264      * {@code short} value.
265      * If a new {@code Short} instance is not required, this method
266      * should generally be used in preference to the constructor
267      * {@link #Short(short)}, as this method is likely to yield
268      * significantly better space and time performance by caching
269      * frequently requested values.
270      *
271      * This method will always cache values in the range -128 to 127,
272      * inclusive, and may cache other values outside of this range.
273      *
274      * @param  s a short value.
275      * @return a {@code Short} instance representing {@code s}.
276      * @since  1.5
277      */
278     @IntrinsicCandidate
valueOf(short s)279     public static Short valueOf(short s) {
280         final int offset = 128;
281         int sAsInt = s;
282         if (sAsInt >= -128 && sAsInt <= 127) { // must cache
283             return ShortCache.cache[sAsInt + offset];
284         }
285         return new Short(s);
286     }
287 
288     /**
289      * Decodes a {@code String} into a {@code Short}.
290      * Accepts decimal, hexadecimal, and octal numbers given by
291      * the following grammar:
292      *
293      * <blockquote>
294      * <dl>
295      * <dt><i>DecodableString:</i>
296      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
297      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
298      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
299      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
300      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
301      *
302      * <dt><i>Sign:</i>
303      * <dd>{@code -}
304      * <dd>{@code +}
305      * </dl>
306      * </blockquote>
307      *
308      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
309      * are as defined in section {@jls 3.10.1} of
310      * <cite>The Java Language Specification</cite>,
311      * except that underscores are not accepted between digits.
312      *
313      * <p>The sequence of characters following an optional
314      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
315      * "{@code #}", or leading zero) is parsed as by the {@code
316      * Short.parseShort} method with the indicated radix (10, 16, or
317      * 8).  This sequence of characters must represent a positive
318      * value or a {@link NumberFormatException} will be thrown.  The
319      * result is negated if first character of the specified {@code
320      * String} is the minus sign.  No whitespace characters are
321      * permitted in the {@code String}.
322      *
323      * @param     nm the {@code String} to decode.
324      * @return    a {@code Short} object holding the {@code short}
325      *            value represented by {@code nm}
326      * @throws    NumberFormatException  if the {@code String} does not
327      *            contain a parsable {@code short}.
328      * @see java.lang.Short#parseShort(java.lang.String, int)
329      */
decode(String nm)330     public static Short decode(String nm) throws NumberFormatException {
331         int i = Integer.decode(nm);
332         if (i < MIN_VALUE || i > MAX_VALUE)
333             throw new NumberFormatException(
334                     "Value " + i + " out of range from input " + nm);
335         return valueOf((short)i);
336     }
337 
338     /**
339      * The value of the {@code Short}.
340      *
341      * @serial
342      */
343     private final short value;
344 
345     /**
346      * Constructs a newly allocated {@code Short} object that
347      * represents the specified {@code short} value.
348      *
349      * @param value     the value to be represented by the
350      *                  {@code Short}.
351      *
352      * @deprecated
353      * It is rarely appropriate to use this constructor. The static factory
354      * {@link #valueOf(short)} is generally a better choice, as it is
355      * likely to yield significantly better space and time performance.
356      */
357     // Android-changed: not yet forRemoval on Android.
358     @Deprecated(since="9"/*, forRemoval = true*/)
Short(short value)359     public Short(short value) {
360         this.value = value;
361     }
362 
363     /**
364      * Constructs a newly allocated {@code Short} object that
365      * represents the {@code short} value indicated by the
366      * {@code String} parameter. The string is converted to a
367      * {@code short} value in exactly the manner used by the
368      * {@code parseShort} method for radix 10.
369      *
370      * @param s the {@code String} to be converted to a
371      *          {@code Short}
372      * @throws  NumberFormatException If the {@code String}
373      *          does not contain a parsable {@code short}.
374      *
375      * @deprecated
376      * It is rarely appropriate to use this constructor.
377      * Use {@link #parseShort(String)} to convert a string to a
378      * {@code short} primitive, or use {@link #valueOf(String)}
379      * to convert a string to a {@code Short} object.
380      */
381     // Android-changed: not yet forRemoval on Android.
382     @Deprecated(since="9"/*, forRemoval = true*/)
Short(String s)383     public Short(String s) throws NumberFormatException {
384         this.value = parseShort(s, 10);
385     }
386 
387     /**
388      * Returns the value of this {@code Short} as a {@code byte} after
389      * a narrowing primitive conversion.
390      * @jls 5.1.3 Narrowing Primitive Conversion
391      */
byteValue()392     public byte byteValue() {
393         return (byte)value;
394     }
395 
396     /**
397      * Returns the value of this {@code Short} as a
398      * {@code short}.
399      */
400     @IntrinsicCandidate
shortValue()401     public short shortValue() {
402         return value;
403     }
404 
405     /**
406      * Returns the value of this {@code Short} as an {@code int} after
407      * a widening primitive conversion.
408      * @jls 5.1.2 Widening Primitive Conversion
409      */
intValue()410     public int intValue() {
411         return (int)value;
412     }
413 
414     /**
415      * Returns the value of this {@code Short} as a {@code long} after
416      * a widening primitive conversion.
417      * @jls 5.1.2 Widening Primitive Conversion
418      */
longValue()419     public long longValue() {
420         return (long)value;
421     }
422 
423     /**
424      * Returns the value of this {@code Short} as a {@code float}
425      * after a widening primitive conversion.
426      * @jls 5.1.2 Widening Primitive Conversion
427      */
floatValue()428     public float floatValue() {
429         return (float)value;
430     }
431 
432     /**
433      * Returns the value of this {@code Short} as a {@code double}
434      * after a widening primitive conversion.
435      * @jls 5.1.2 Widening Primitive Conversion
436      */
doubleValue()437     public double doubleValue() {
438         return (double)value;
439     }
440 
441     /**
442      * Returns a {@code String} object representing this
443      * {@code Short}'s value.  The value is converted to signed
444      * decimal representation and returned as a string, exactly as if
445      * the {@code short} value were given as an argument to the
446      * {@link java.lang.Short#toString(short)} method.
447      *
448      * @return  a string representation of the value of this object in
449      *          base&nbsp;10.
450      */
toString()451     public String toString() {
452         return Integer.toString((int)value);
453     }
454 
455     /**
456      * Returns a hash code for this {@code Short}; equal to the result
457      * of invoking {@code intValue()}.
458      *
459      * @return a hash code value for this {@code Short}
460      */
461     @Override
hashCode()462     public int hashCode() {
463         return Short.hashCode(value);
464     }
465 
466     /**
467      * Returns a hash code for a {@code short} value; compatible with
468      * {@code Short.hashCode()}.
469      *
470      * @param value the value to hash
471      * @return a hash code value for a {@code short} value.
472      * @since 1.8
473      */
hashCode(short value)474     public static int hashCode(short value) {
475         return (int)value;
476     }
477 
478     /**
479      * Compares this object to the specified object.  The result is
480      * {@code true} if and only if the argument is not
481      * {@code null} and is a {@code Short} object that
482      * contains the same {@code short} value as this object.
483      *
484      * @param obj       the object to compare with
485      * @return          {@code true} if the objects are the same;
486      *                  {@code false} otherwise.
487      */
equals(Object obj)488     public boolean equals(Object obj) {
489         if (obj instanceof Short) {
490             return value == ((Short)obj).shortValue();
491         }
492         return false;
493     }
494 
495     /**
496      * Compares two {@code Short} objects numerically.
497      *
498      * @param   anotherShort   the {@code Short} to be compared.
499      * @return  the value {@code 0} if this {@code Short} is
500      *          equal to the argument {@code Short}; a value less than
501      *          {@code 0} if this {@code Short} is numerically less
502      *          than the argument {@code Short}; and a value greater than
503      *           {@code 0} if this {@code Short} is numerically
504      *           greater than the argument {@code Short} (signed
505      *           comparison).
506      * @since   1.2
507      */
compareTo(Short anotherShort)508     public int compareTo(Short anotherShort) {
509         return compare(this.value, anotherShort.value);
510     }
511 
512     /**
513      * Compares two {@code short} values numerically.
514      * The value returned is identical to what would be returned by:
515      * <pre>
516      *    Short.valueOf(x).compareTo(Short.valueOf(y))
517      * </pre>
518      *
519      * @param  x the first {@code short} to compare
520      * @param  y the second {@code short} to compare
521      * @return the value {@code 0} if {@code x == y};
522      *         a value less than {@code 0} if {@code x < y}; and
523      *         a value greater than {@code 0} if {@code x > y}
524      * @since 1.7
525      */
compare(short x, short y)526     public static int compare(short x, short y) {
527         return x - y;
528     }
529 
530     /**
531      * Compares two {@code short} values numerically treating the values
532      * as unsigned.
533      *
534      * @param  x the first {@code short} to compare
535      * @param  y the second {@code short} to compare
536      * @return the value {@code 0} if {@code x == y}; a value less
537      *         than {@code 0} if {@code x < y} as unsigned values; and
538      *         a value greater than {@code 0} if {@code x > y} as
539      *         unsigned values
540      * @since 9
541      */
compareUnsigned(short x, short y)542     public static int compareUnsigned(short x, short y) {
543         return Short.toUnsignedInt(x) - Short.toUnsignedInt(y);
544     }
545 
546     /**
547      * The number of bits used to represent a {@code short} value in two's
548      * complement binary form.
549      * @since 1.5
550      */
551     public static final int SIZE = 16;
552 
553     /**
554      * The number of bytes used to represent a {@code short} value in two's
555      * complement binary form.
556      *
557      * @since 1.8
558      */
559     public static final int BYTES = SIZE / Byte.SIZE;
560 
561     /**
562      * Returns the value obtained by reversing the order of the bytes in the
563      * two's complement representation of the specified {@code short} value.
564      *
565      * @param i the value whose bytes are to be reversed
566      * @return the value obtained by reversing (or, equivalently, swapping)
567      *     the bytes in the specified {@code short} value.
568      * @since 1.5
569      */
570     @IntrinsicCandidate
reverseBytes(short i)571     public static short reverseBytes(short i) {
572         return (short) (((i & 0xFF00) >> 8) | (i << 8));
573     }
574 
575 
576     /**
577      * Converts the argument to an {@code int} by an unsigned
578      * conversion.  In an unsigned conversion to an {@code int}, the
579      * high-order 16 bits of the {@code int} are zero and the
580      * low-order 16 bits are equal to the bits of the {@code short} argument.
581      *
582      * Consequently, zero and positive {@code short} values are mapped
583      * to a numerically equal {@code int} value and negative {@code
584      * short} values are mapped to an {@code int} value equal to the
585      * input plus 2<sup>16</sup>.
586      *
587      * @param  x the value to convert to an unsigned {@code int}
588      * @return the argument converted to {@code int} by an unsigned
589      *         conversion
590      * @since 1.8
591      */
toUnsignedInt(short x)592     public static int toUnsignedInt(short x) {
593         return ((int) x) & 0xffff;
594     }
595 
596     /**
597      * Converts the argument to a {@code long} by an unsigned
598      * conversion.  In an unsigned conversion to a {@code long}, the
599      * high-order 48 bits of the {@code long} are zero and the
600      * low-order 16 bits are equal to the bits of the {@code short} argument.
601      *
602      * Consequently, zero and positive {@code short} values are mapped
603      * to a numerically equal {@code long} value and negative {@code
604      * short} values are mapped to a {@code long} value equal to the
605      * input plus 2<sup>16</sup>.
606      *
607      * @param  x the value to convert to an unsigned {@code long}
608      * @return the argument converted to {@code long} by an unsigned
609      *         conversion
610      * @since 1.8
611      */
toUnsignedLong(short x)612     public static long toUnsignedLong(short x) {
613         return ((long) x) & 0xffffL;
614     }
615 
616     /** use serialVersionUID from JDK 1.1. for interoperability */
617     @java.io.Serial
618     private static final long serialVersionUID = 7515723908773894738L;
619 }
620