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 {@linkplain #equals(Object) equal}
 54  * as interchangeable and should not use instances for synchronization, mutexes, or
 55  * with {@linkplain java.lang.ref.Reference object references}.
 56  *
 57  * <div class="preview-block">
 58  *      <div class="preview-comment">
 59  *          When preview features are enabled, {@code Short} is a {@linkplain Class#isValue value class}.
 60  *          Use of value class instances for synchronization, mutexes, or with
 61  *          {@linkplain java.lang.ref.Reference object references} result in
 62  *          {@link IdentityException}.
 63  *      </div>
 64  * </div>
 65  *
 66  * @author  Nakul Saraiya
 67  * @author  Joseph D. Darcy
 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     private static final class ShortCache {
245         private ShortCache() {}
246 
247         @Stable
248         static final Short[] cache;
249         static Short[] archivedCache;
250 
251         static {
252             int size = -(-128) + 127 + 1;
253 
254             // Load and use the archived cache if it exists
255             CDS.initializeFromArchive(ShortCache.class);
256             if (archivedCache == null) {
257                 Short[] c = new Short[size];
258                 short value = -128;
259                 for(int i = 0; i < size; i++) {
260                     c[i] = new Short(value++);
261                 }
262                 archivedCache = c;
263             }
264             cache = archivedCache;
265             assert cache.length == size;
266         }
267     }
268 
269     /**
270      * Returns a {@code Short} instance representing the specified
271      * {@code short} value.
272      * If a new {@code Short} instance is not required, this method
273      * should generally be used in preference to the constructor
274      * {@link #Short(short)}, as this method is likely to yield
275      * significantly better space and time performance by caching
276      * frequently requested values.
277      *
278      * This method will always cache values in the range -128 to 127,
279      * inclusive, and may cache other values outside of this range.
280      *
281      * @param  s a short value.
282      * @return a {@code Short} instance representing {@code s}.
283      * @since  1.5
284      */
285     @IntrinsicCandidate
286     @DeserializeConstructor
287     public static Short valueOf(short s) {
288         final int offset = 128;
289         int sAsInt = s;
290         if (sAsInt >= -128 && sAsInt <= 127) { // must cache
291             return ShortCache.cache[sAsInt + offset];
292         }
293         return new Short(s);
294     }
295 
296     /**
297      * Decodes a {@code String} into a {@code Short}.
298      * Accepts decimal, hexadecimal, and octal numbers given by
299      * the following grammar:
300      *
301      * <blockquote>
302      * <dl>
303      * <dt><i>DecodableString:</i>
304      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
305      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
306      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
307      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
308      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
309      *
310      * <dt><i>Sign:</i>
311      * <dd>{@code -}
312      * <dd>{@code +}
313      * </dl>
314      * </blockquote>
315      *
316      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
317      * are as defined in section {@jls 3.10.1} of
318      * <cite>The Java Language Specification</cite>,
319      * except that underscores are not accepted between digits.
320      *
321      * <p>The sequence of characters following an optional
322      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
323      * "{@code #}", or leading zero) is parsed as by the {@code
324      * Short.parseShort} method with the indicated radix (10, 16, or
325      * 8).  This sequence of characters must represent a positive
326      * value or a {@link NumberFormatException} will be thrown.  The
327      * result is negated if first character of the specified {@code
328      * String} is the minus sign.  No whitespace characters are
329      * permitted in the {@code String}.
330      *
331      * @param     nm the {@code String} to decode.
332      * @return    a {@code Short} object holding the {@code short}
333      *            value represented by {@code nm}
334      * @throws    NumberFormatException  if the {@code String} does not
335      *            contain a parsable {@code short}.
336      * @see java.lang.Short#parseShort(java.lang.String, int)
337      */
338     public static Short decode(String nm) throws NumberFormatException {
339         int i = Integer.decode(nm);
340         if (i < MIN_VALUE || i > MAX_VALUE)
341             throw new NumberFormatException(
342                     "Value " + i + " out of range from input " + nm);
343         return valueOf((short)i);
344     }
345 
346     /**
347      * The value of the {@code Short}.
348      *
349      * @serial
350      */
351     private final short value;
352 
353     /**
354      * Constructs a newly allocated {@code Short} object that
355      * represents the specified {@code short} value.
356      *
357      * @param value     the value to be represented by the
358      *                  {@code Short}.
359      *
360      * @deprecated
361      * It is rarely appropriate to use this constructor. The static factory
362      * {@link #valueOf(short)} is generally a better choice, as it is
363      * likely to yield significantly better space and time performance.
364      */
365     @Deprecated(since="9", forRemoval = true)
366     public Short(short value) {
367         this.value = value;
368     }
369 
370     /**
371      * Constructs a newly allocated {@code Short} object that
372      * represents the {@code short} value indicated by the
373      * {@code String} parameter. The string is converted to a
374      * {@code short} value in exactly the manner used by the
375      * {@code parseShort} method for radix 10.
376      *
377      * @param s the {@code String} to be converted to a
378      *          {@code Short}
379      * @throws  NumberFormatException If the {@code String}
380      *          does not contain a parsable {@code short}.
381      *
382      * @deprecated
383      * It is rarely appropriate to use this constructor.
384      * Use {@link #parseShort(String)} to convert a string to a
385      * {@code short} primitive, or use {@link #valueOf(String)}
386      * to convert a string to a {@code Short} object.
387      */
388     @Deprecated(since="9", forRemoval = true)
389     public Short(String s) throws NumberFormatException {
390         this.value = parseShort(s, 10);
391     }
392 
393     /**
394      * Returns the value of this {@code Short} as a {@code byte} after
395      * a narrowing primitive conversion.
396      * @jls 5.1.3 Narrowing Primitive Conversion
397      */
398     public byte byteValue() {
399         return (byte)value;
400     }
401 
402     /**
403      * Returns the value of this {@code Short} as a
404      * {@code short}.
405      */
406     @IntrinsicCandidate
407     public short shortValue() {
408         return value;
409     }
410 
411     /**
412      * Returns the value of this {@code Short} as an {@code int} after
413      * a widening primitive conversion.
414      * @jls 5.1.2 Widening Primitive Conversion
415      */
416     public int intValue() {
417         return (int)value;
418     }
419 
420     /**
421      * Returns the value of this {@code Short} as a {@code long} after
422      * a widening primitive conversion.
423      * @jls 5.1.2 Widening Primitive Conversion
424      */
425     public long longValue() {
426         return (long)value;
427     }
428 
429     /**
430      * Returns the value of this {@code Short} as a {@code float}
431      * after a widening primitive conversion.
432      * @jls 5.1.2 Widening Primitive Conversion
433      */
434     public float floatValue() {
435         return (float)value;
436     }
437 
438     /**
439      * Returns the value of this {@code Short} as a {@code double}
440      * after a widening primitive conversion.
441      * @jls 5.1.2 Widening Primitive Conversion
442      */
443     public double doubleValue() {
444         return (double)value;
445     }
446 
447     /**
448      * Returns a {@code String} object representing this
449      * {@code Short}'s value.  The value is converted to signed
450      * decimal representation and returned as a string, exactly as if
451      * the {@code short} value were given as an argument to the
452      * {@link java.lang.Short#toString(short)} method.
453      *
454      * @return  a string representation of the value of this object in
455      *          base&nbsp;10.
456      */
457     @Override
458     public String toString() {
459         return Integer.toString(value);
460     }
461 
462     /**
463      * Returns a hash code for this {@code Short}; equal to the result
464      * of invoking {@code intValue()}.
465      *
466      * @return a hash code value for this {@code Short}
467      */
468     @Override
469     public int hashCode() {
470         return Short.hashCode(value);
471     }
472 
473     /**
474      * Returns a hash code for a {@code short} value; compatible with
475      * {@code Short.hashCode()}.
476      *
477      * @param value the value to hash
478      * @return a hash code value for a {@code short} value.
479      * @since 1.8
480      */
481     public static int hashCode(short value) {
482         return (int)value;
483     }
484 
485     /**
486      * Compares this object to the specified object.  The result is
487      * {@code true} if and only if the argument is not
488      * {@code null} and is a {@code Short} object that
489      * contains the same {@code short} value as this object.
490      *
491      * @param obj       the object to compare with
492      * @return          {@code true} if the objects are the same;
493      *                  {@code false} otherwise.
494      */
495     public boolean equals(Object obj) {
496         if (obj instanceof Short s) {
497             return value == s.shortValue();
498         }
499         return false;
500     }
501 
502     /**
503      * Compares two {@code Short} objects numerically.
504      *
505      * @param   anotherShort   the {@code Short} to be compared.
506      * @return  the value {@code 0} if this {@code Short} is
507      *          equal to the argument {@code Short}; a value less than
508      *          {@code 0} if this {@code Short} is numerically less
509      *          than the argument {@code Short}; and a value greater than
510      *           {@code 0} if this {@code Short} is numerically
511      *           greater than the argument {@code Short} (signed
512      *           comparison).
513      * @since   1.2
514      */
515     public int compareTo(Short anotherShort) {
516         return compare(this.value, anotherShort.value);
517     }
518 
519     /**
520      * Compares two {@code short} values numerically.
521      * The value returned is identical to what would be returned by:
522      * <pre>
523      *    Short.valueOf(x).compareTo(Short.valueOf(y))
524      * </pre>
525      *
526      * @param  x the first {@code short} to compare
527      * @param  y the second {@code short} to compare
528      * @return the value {@code 0} if {@code x == y};
529      *         a value less than {@code 0} if {@code x < y}; and
530      *         a value greater than {@code 0} if {@code x > y}
531      * @since 1.7
532      */
533     public static int compare(short x, short y) {
534         return x - y;
535     }
536 
537     /**
538      * Compares two {@code short} values numerically treating the values
539      * as unsigned.
540      *
541      * @param  x the first {@code short} to compare
542      * @param  y the second {@code short} to compare
543      * @return the value {@code 0} if {@code x == y}; a value less
544      *         than {@code 0} if {@code x < y} as unsigned values; and
545      *         a value greater than {@code 0} if {@code x > y} as
546      *         unsigned values
547      * @since 9
548      */
549     public static int compareUnsigned(short x, short y) {
550         return Short.toUnsignedInt(x) - Short.toUnsignedInt(y);
551     }
552 
553     /**
554      * The number of bits used to represent a {@code short} value in two's
555      * complement binary form.
556      * @since 1.5
557      */
558     public static final int SIZE = 16;
559 
560     /**
561      * The number of bytes used to represent a {@code short} value in two's
562      * complement binary form.
563      *
564      * @since 1.8
565      */
566     public static final int BYTES = SIZE / Byte.SIZE;
567 
568     /**
569      * Returns the value obtained by reversing the order of the bytes in the
570      * two's complement representation of the specified {@code short} value.
571      *
572      * @param i the value whose bytes are to be reversed
573      * @return the value obtained by reversing (or, equivalently, swapping)
574      *     the bytes in the specified {@code short} value.
575      * @since 1.5
576      */
577     @IntrinsicCandidate
578     public static short reverseBytes(short i) {
579         return (short) (((i & 0xFF00) >> 8) | (i << 8));
580     }
581 
582 
583     /**
584      * Converts the argument to an {@code int} by an unsigned
585      * conversion.  In an unsigned conversion to an {@code int}, the
586      * high-order 16 bits of the {@code int} are zero and the
587      * low-order 16 bits are equal to the bits of the {@code short} argument.
588      *
589      * Consequently, zero and positive {@code short} values are mapped
590      * to a numerically equal {@code int} value and negative {@code
591      * short} values are mapped to an {@code int} value equal to the
592      * input plus 2<sup>16</sup>.
593      *
594      * @param  x the value to convert to an unsigned {@code int}
595      * @return the argument converted to {@code int} by an unsigned
596      *         conversion
597      * @since 1.8
598      */
599     public static int toUnsignedInt(short x) {
600         return ((int) x) & 0xffff;
601     }
602 
603     /**
604      * Converts the argument to a {@code long} by an unsigned
605      * conversion.  In an unsigned conversion to a {@code long}, the
606      * high-order 48 bits of the {@code long} are zero and the
607      * low-order 16 bits are equal to the bits of the {@code short} argument.
608      *
609      * Consequently, zero and positive {@code short} values are mapped
610      * to a numerically equal {@code long} value and negative {@code
611      * short} values are mapped to a {@code long} value equal to the
612      * input plus 2<sup>16</sup>.
613      *
614      * @param  x the value to convert to an unsigned {@code long}
615      * @return the argument converted to {@code long} by an unsigned
616      *         conversion
617      * @since 1.8
618      */
619     public static long toUnsignedLong(short x) {
620         return ((long) x) & 0xffffL;
621     }
622 
623     /** use serialVersionUID from JDK 1.1. for interoperability */
624     @java.io.Serial
625     private static final long serialVersionUID = 7515723908773894738L;
626 }