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