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