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