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.vm.annotation.IntrinsicCandidate;
 30 import jdk.internal.vm.annotation.Stable;
 31 
 32 import java.lang.constant.Constable;
 33 import java.lang.constant.DynamicConstantDesc;
 34 import java.util.Optional;
 35 
 36 import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;
 37 import static java.lang.constant.ConstantDescs.CD_int;
 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.ValueBased
 63 public final class Short extends Number implements Comparable<Short>, Constable {
 64 
 65     /**
 66      * A constant holding the minimum value a {@code short} can
 67      * have, -2<sup>15</sup>.
 68      */
 69     public static final short   MIN_VALUE = -32768;
 70 
 71     /**
 72      * A constant holding the maximum value a {@code short} can
 73      * have, 2<sup>15</sup>-1.
 74      */
 75     public static final short   MAX_VALUE = 32767;
 76 
 77     /**
 78      * The {@code Class} instance representing the primitive type
 79      * {@code short}.
 80      */
 81     @SuppressWarnings("unchecked")
 82     public static final Class<Short>    TYPE = (Class<Short>) Class.getPrimitiveClass("short");
 83 
 84     /**
 85      * Returns a new {@code String} object representing the
 86      * specified {@code short}. The radix is assumed to be 10.
 87      *
 88      * @param s the {@code short} to be converted
 89      * @return the string representation of the specified {@code short}
 90      * @see java.lang.Integer#toString(int)
 91      */
 92     public static String toString(short s) {
 93         return Integer.toString(s);
 94     }
 95 
 96     /**
 97      * Parses the string argument as a signed {@code short} in the
 98      * radix specified by the second argument. The characters in the
 99      * string must all be digits, of the specified radix (as
100      * determined by whether {@link java.lang.Character#digit(char,
101      * int)} returns a nonnegative value) except that the first
102      * character may be an ASCII minus sign {@code '-'}
103      * ({@code '\u005Cu002D'}) to indicate a negative value or an
104      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
105      * indicate a positive value.  The resulting {@code short} value
106      * is returned.
107      *
108      * <p>An exception of type {@code NumberFormatException} is
109      * thrown if any of the following situations occurs:
110      * <ul>
111      * <li> The first argument is {@code null} or is a string of
112      * length zero.
113      *
114      * <li> The radix is either smaller than {@link
115      * java.lang.Character#MIN_RADIX} or larger than {@link
116      * java.lang.Character#MAX_RADIX}.
117      *
118      * <li> Any character of the string is not a digit of the
119      * specified radix, except that the first character may be a minus
120      * sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
121      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
122      * string is longer than length 1.
123      *
124      * <li> The value represented by the string is not a value of type
125      * {@code short}.
126      * </ul>
127      *
128      * @param s         the {@code String} containing the
129      *                  {@code short} representation to be parsed
130      * @param radix     the radix to be used while parsing {@code s}
131      * @return          the {@code short} represented by the string
132      *                  argument in the specified radix.
133      * @throws          NumberFormatException If the {@code String}
134      *                  does not contain a parsable {@code short}.
135      */
136     public static short parseShort(String s, int radix)
137         throws NumberFormatException {
138         int i = Integer.parseInt(s, radix);
139         if (i < MIN_VALUE || i > MAX_VALUE)
140             throw new NumberFormatException(
141                 "Value out of range. Value:\"" + s + "\" Radix:" + radix);
142         return (short)i;
143     }
144 
145     /**
146      * Parses the string argument as a signed decimal {@code
147      * short}. The characters in the string must all be decimal
148      * digits, except that the first character may be an ASCII minus
149      * sign {@code '-'} ({@code '\u005Cu002D'}) to indicate a
150      * negative value or an ASCII plus sign {@code '+'}
151      * ({@code '\u005Cu002B'}) to indicate a positive value.  The
152      * resulting {@code short} value is returned, exactly as if the
153      * argument and the radix 10 were given as arguments to the {@link
154      * #parseShort(java.lang.String, int)} method.
155      *
156      * @param s a {@code String} containing the {@code short}
157      *          representation to be parsed
158      * @return  the {@code short} value represented by the
159      *          argument in decimal.
160      * @throws  NumberFormatException If the string does not
161      *          contain a parsable {@code short}.
162      */
163     public static short parseShort(String s) throws NumberFormatException {
164         return parseShort(s, 10);
165     }
166 
167     /**
168      * Returns a {@code Short} object holding the value
169      * extracted from the specified {@code String} when parsed
170      * with the radix given by the second argument. The first argument
171      * is interpreted as representing a signed {@code short} in
172      * the radix specified by the second argument, exactly as if the
173      * argument were given to the {@link #parseShort(java.lang.String,
174      * int)} method. The result is a {@code Short} object that
175      * represents the {@code short} value specified by the string.
176      *
177      * <p>In other words, this method returns a {@code Short} object
178      * equal to the value of:
179      *
180      * <blockquote>
181      *  {@code Short.valueOf(Short.parseShort(s, radix))}
182      * </blockquote>
183      *
184      * @param s         the string to be parsed
185      * @param radix     the radix to be used in interpreting {@code s}
186      * @return          a {@code Short} object holding the value
187      *                  represented by the string argument in the
188      *                  specified radix.
189      * @throws          NumberFormatException If the {@code String} does
190      *                  not contain a parsable {@code short}.
191      */
192     public static Short valueOf(String s, int radix)
193         throws NumberFormatException {
194         return valueOf(parseShort(s, radix));
195     }
196 
197     /**
198      * Returns a {@code Short} object holding the
199      * value given by the specified {@code String}. The argument
200      * is interpreted as representing a signed decimal
201      * {@code short}, exactly as if the argument were given to
202      * the {@link #parseShort(java.lang.String)} method. The result is
203      * a {@code Short} object that represents the
204      * {@code short} value specified by the string.
205      *
206      * <p>In other words, this method returns a {@code Short} object
207      * equal to the value of:
208      *
209      * <blockquote>
210      *  {@code Short.valueOf(Short.parseShort(s))}
211      * </blockquote>
212      *
213      * @param s the string to be parsed
214      * @return  a {@code Short} object holding the value
215      *          represented by the string argument
216      * @throws  NumberFormatException If the {@code String} does
217      *          not contain a parsable {@code short}.
218      */
219     public static Short valueOf(String s) throws NumberFormatException {
220         return valueOf(s, 10);
221     }
222 
223     /**
224      * Returns an {@link Optional} containing the nominal descriptor for this
225      * instance.
226      *
227      * @return an {@link Optional} describing the {@linkplain Short} instance
228      * @since 15
229      */
230     @Override
231     public Optional<DynamicConstantDesc<Short>> describeConstable() {
232         return Optional.of(DynamicConstantDesc.ofNamed(BSM_EXPLICIT_CAST, DEFAULT_NAME, CD_short, intValue()));
233     }
234 
235     private static final class ShortCache {
236         private ShortCache() {}
237 
238         @Stable
239         static final Short[] cache;
240         static Short[] archivedCache;
241 
242         static {
243             int size = -(-128) + 127 + 1;
244 
245             // Load and use the archived cache if it exists
246             CDS.initializeFromArchive(ShortCache.class);
247             if (archivedCache == null || archivedCache.length != size) {
248                 Short[] c = new Short[size];
249                 short value = -128;
250                 for(int i = 0; i < size; i++) {
251                     c[i] = new Short(value++);
252                 }
253                 archivedCache = c;
254             }
255             cache = archivedCache;
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", forRemoval = true)
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", forRemoval = true)
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) {
486             return value == ((Short)obj).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 }