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