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