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