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