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