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