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