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