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