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