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