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