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