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