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