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