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