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