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.IntrinsicCandidate;
 32 import jdk.internal.vm.annotation.Stable;
 33 
 34 import java.lang.constant.Constable;
 35 import java.lang.constant.DynamicConstantDesc;
 36 import java.util.Optional;
 37 
 38 import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;
 39 import static java.lang.constant.ConstantDescs.CD_short;
 40 import static java.lang.constant.ConstantDescs.DEFAULT_NAME;
 41 
 42 /**
 43  * The {@code Short} class is the {@linkplain
 44  * java.lang##wrapperClass wrapper class} for values of the primitive
 45  * type {@code short}. An object of type {@code Short} contains a
 46  * single field whose type is {@code short}.
 47  *
 48  * <p>In addition, this class provides several methods for converting
 49  * a {@code short} to a {@code String} and a {@code String} to a
 50  * {@code short}, as well as other constants and methods useful when
 51  * dealing with a {@code short}.
 52  *
 53  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 54  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
 55  * as interchangeable and should not use instances for synchronization, mutexes, or
 56  * with {@linkplain java.lang.ref.Reference object references}.
 57  *
 58  * <div class="preview-block">
 59  *      <div class="preview-comment">
 60  *          When preview features are enabled, {@code Short} is a {@linkplain Class#isValue value class}.
 61  *          Use of value class instances for synchronization, mutexes, or with
 62  *          {@linkplain java.lang.ref.Reference object references} result in
 63  *          {@link IdentityException}.
 64  *      </div>
 65  * </div>
 66  *
 67  * @author  Nakul Saraiya
 68  * @author  Joseph D. Darcy
 69  * @see     java.lang.Number
 70  * @since   1.1
 71  */
 72 @jdk.internal.MigratedValueClass
 73 @jdk.internal.ValueBased
 74 public final class Short extends Number implements Comparable<Short>, Constable {
 75 
 76     /**
 77      * A constant holding the minimum value a {@code short} can
 78      * have, -2<sup>15</sup>.
 79      */
 80     public static final short   MIN_VALUE = -32768;
 81 
 82     /**
 83      * A constant holding the maximum value a {@code short} can
 84      * have, 2<sup>15</sup>-1.
 85      */
 86     public static final short   MAX_VALUE = 32767;
 87 
 88     /**
 89      * The {@code Class} instance representing the primitive type
 90      * {@code short}.
 91      */
 92     public static final Class<Short> TYPE = Class.getPrimitiveClass("short");
 93 
 94     /**
 95      * Returns a new {@code String} object representing the
 96      * specified {@code short}. The radix is assumed to be 10.
 97      *
 98      * @param s the {@code short} to be converted
 99      * @return the string representation of the specified {@code short}
100      * @see java.lang.Integer#toString(int)
101      */
102     public static String toString(short s) {
103         return Integer.toString(s);
104     }
105 
106     /**
107      * Parses the string argument as a signed {@code short} in the
108      * radix specified by the second argument. The characters in the
109      * string must all be digits, of the specified radix (as
110      * determined by whether {@link java.lang.Character#digit(char,
111      * int)} returns a nonnegative value) except that the first
112      * character may be an ASCII minus sign {@code '-'}
113      * ({@code '\u005Cu002D'}) to indicate a negative value or an
114      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
115      * indicate a positive value.  The resulting {@code short} value
116      * is returned.
117      *
118      * <p>An exception of type {@code NumberFormatException} is
119      * thrown if any of the following situations occurs:
120      * <ul>
121      * <li> The first argument is {@code null} or is a string of
122      * length zero.
123      *
124      * <li> The radix is either smaller than {@link
125      * java.lang.Character#MIN_RADIX} or larger than {@link
126      * java.lang.Character#MAX_RADIX}.
127      *
128      * <li> Any character of the string is not a digit of the
129      * specified radix, except that the first character may be a minus
130      * sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
131      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
132      * string is longer than length 1.
133      *
134      * <li> The value represented by the string is not a value of type
135      * {@code short}.
136      * </ul>
137      *
138      * @param s         the {@code String} containing the
139      *                  {@code short} representation to be parsed
140      * @param radix     the radix to be used while parsing {@code s}
141      * @return          the {@code short} represented by the string
142      *                  argument in the specified radix.
143      * @throws          NumberFormatException If the {@code String}
144      *                  does not contain a parsable {@code short}.
145      */
146     public static short parseShort(String s, int radix)
147         throws NumberFormatException {
148         int i = Integer.parseInt(s, radix);
149         if (i < MIN_VALUE || i > MAX_VALUE)
150             throw new NumberFormatException(
151                 "Value out of range. Value:\"" + s + "\" Radix:" + radix);
152         return (short)i;
153     }
154 
155     /**
156      * Parses the string argument as a signed decimal {@code
157      * short}. The characters in the string must all be decimal
158      * digits, except that the first character may be an ASCII minus
159      * sign {@code '-'} ({@code '\u005Cu002D'}) to indicate a
160      * negative value or an ASCII plus sign {@code '+'}
161      * ({@code '\u005Cu002B'}) to indicate a positive value.  The
162      * resulting {@code short} value is returned, exactly as if the
163      * argument and the radix 10 were given as arguments to the {@link
164      * #parseShort(java.lang.String, int)} method.
165      *
166      * @param s a {@code String} containing the {@code short}
167      *          representation to be parsed
168      * @return  the {@code short} value represented by the
169      *          argument in decimal.
170      * @throws  NumberFormatException If the string does not
171      *          contain a parsable {@code short}.
172      */
173     public static short parseShort(String s) throws NumberFormatException {
174         return parseShort(s, 10);
175     }
176 
177     /**
178      * Returns a {@code Short} object holding the value
179      * extracted from the specified {@code String} when parsed
180      * with the radix given by the second argument. The first argument
181      * is interpreted as representing a signed {@code short} in
182      * the radix specified by the second argument, exactly as if the
183      * argument were given to the {@link #parseShort(java.lang.String,
184      * int)} method. The result is a {@code Short} object that
185      * represents the {@code short} value specified by the string.
186      *
187      * <p>In other words, this method returns a {@code Short} object
188      * equal to the value of:
189      *
190      * <blockquote>
191      *  {@code Short.valueOf(Short.parseShort(s, radix))}
192      * </blockquote>
193      *
194      * @param s         the string to be parsed
195      * @param radix     the radix to be used in interpreting {@code s}
196      * @return          a {@code Short} object holding the value
197      *                  represented by the string argument in the
198      *                  specified radix.
199      * @throws          NumberFormatException If the {@code String} does
200      *                  not contain a parsable {@code short}.
201      */
202     public static Short valueOf(String s, int radix)
203         throws NumberFormatException {
204         return valueOf(parseShort(s, radix));
205     }
206 
207     /**
208      * Returns a {@code Short} object holding the
209      * value given by the specified {@code String}. The argument
210      * is interpreted as representing a signed decimal
211      * {@code short}, exactly as if the argument were given to
212      * the {@link #parseShort(java.lang.String)} method. The result is
213      * a {@code Short} object that represents the
214      * {@code short} value specified by the string.
215      *
216      * <p>In other words, this method returns a {@code Short} object
217      * equal to the value of:
218      *
219      * <blockquote>
220      *  {@code Short.valueOf(Short.parseShort(s))}
221      * </blockquote>
222      *
223      * @param s the string to be parsed
224      * @return  a {@code Short} object holding the value
225      *          represented by the string argument
226      * @throws  NumberFormatException If the {@code String} does
227      *          not contain a parsable {@code short}.
228      */
229     public static Short valueOf(String s) throws NumberFormatException {
230         return valueOf(s, 10);
231     }
232 
233     /**
234      * Returns an {@link Optional} containing the nominal descriptor for this
235      * instance.
236      *
237      * @return an {@link Optional} describing the {@linkplain Short} instance
238      * @since 15
239      */
240     @Override
241     public Optional<DynamicConstantDesc<Short>> describeConstable() {
242         return Optional.of(DynamicConstantDesc.ofNamed(BSM_EXPLICIT_CAST, DEFAULT_NAME, CD_short, intValue()));
243     }
244 
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 }