Byte.java revision 1550ed9ba326ce08cef8ebf01699a49fabdc64f3
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.lang;
28
29/**
30 *
31 * The {@code Byte} class wraps a value of primitive type {@code byte}
32 * in an object.  An object of type {@code Byte} contains a single
33 * field whose type is {@code byte}.
34 *
35 * <p>In addition, this class provides several methods for converting
36 * a {@code byte} to a {@code String} and a {@code String} to a {@code
37 * byte}, as well as other constants and methods useful when dealing
38 * with a {@code byte}.
39 *
40 * @author  Nakul Saraiya
41 * @author  Joseph D. Darcy
42 * @see     java.lang.Number
43 * @since   JDK1.1
44 */
45public final class Byte extends Number implements Comparable<Byte> {
46
47    /**
48     * A constant holding the minimum value a {@code byte} can
49     * have, -2<sup>7</sup>.
50     */
51    public static final byte   MIN_VALUE = -128;
52
53    /**
54     * A constant holding the maximum value a {@code byte} can
55     * have, 2<sup>7</sup>-1.
56     */
57    public static final byte   MAX_VALUE = 127;
58
59    /**
60     * The {@code Class} instance representing the primitive type
61     * {@code byte}.
62     */
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     */
73    public static String toString(byte b) {
74        return Integer.toString((int)b, 10);
75    }
76
77    private static class 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     */
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>'&#92;u002D'</code>) to indicate a negative value or an
114     * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) 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>'&#92;u002D'</code>) or plus sign
131     * {@code '+'} (<code>'&#92;u002B'</code>) 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     */
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>'&#92;u002D'</code>) to indicate a negative
161     * value or an ASCII plus sign {@code '+'}
162     * (<code>'&#92;u002B'</code>) 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     */
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     */
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     */
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     * <p>
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     */
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     */
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     */
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     */
323    public byte byteValue() {
324        return value;
325    }
326
327    /**
328     * Returns the value of this {@code Byte} as a
329     * {@code short}.
330     */
331    public short shortValue() {
332        return (short)value;
333    }
334
335    /**
336     * Returns the value of this {@code Byte} as an
337     * {@code int}.
338     */
339    public int intValue() {
340        return (int)value;
341    }
342
343    /**
344     * Returns the value of this {@code Byte} as a
345     * {@code long}.
346     */
347    public long longValue() {
348        return (long)value;
349    }
350
351    /**
352     * Returns the value of this {@code Byte} as a
353     * {@code float}.
354     */
355    public float floatValue() {
356        return (float)value;
357    }
358
359    /**
360     * Returns the value of this {@code Byte} as a
361     * {@code double}.
362     */
363    public double doubleValue() {
364        return (double)value;
365    }
366
367    /**
368     * Returns a {@code String} object representing this
369     * {@code Byte}'s value.  The value is converted to signed
370     * decimal representation and returned as a string, exactly as if
371     * the {@code byte} value were given as an argument to the
372     * {@link java.lang.Byte#toString(byte)} method.
373     *
374     * @return  a string representation of the value of this object in
375     *          base&nbsp;10.
376     */
377    public String toString() {
378        return Integer.toString((int)value);
379    }
380
381    /**
382     * Returns a hash code for this {@code Byte}; equal to the result
383     * of invoking {@code intValue()}.
384     *
385     * @return a hash code value for this {@code Byte}
386     */
387    public int hashCode() {
388        return (int)value;
389    }
390
391    /**
392     * Compares this object to the specified object.  The result is
393     * {@code true} if and only if the argument is not
394     * {@code null} and is a {@code Byte} object that
395     * contains the same {@code byte} value as this object.
396     *
397     * @param obj       the object to compare with
398     * @return          {@code true} if the objects are the same;
399     *                  {@code false} otherwise.
400     */
401    public boolean equals(Object obj) {
402        if (obj instanceof Byte) {
403            return value == ((Byte)obj).byteValue();
404        }
405        return false;
406    }
407
408    /**
409     * Compares two {@code Byte} objects numerically.
410     *
411     * @param   anotherByte   the {@code Byte} to be compared.
412     * @return  the value {@code 0} if this {@code Byte} is
413     *          equal to the argument {@code Byte}; a value less than
414     *          {@code 0} if this {@code Byte} is numerically less
415     *          than the argument {@code Byte}; and a value greater than
416     *           {@code 0} if this {@code Byte} is numerically
417     *           greater than the argument {@code Byte} (signed
418     *           comparison).
419     * @since   1.2
420     */
421    public int compareTo(Byte anotherByte) {
422        return compare(this.value, anotherByte.value);
423    }
424
425    /**
426     * Compares two {@code byte} values numerically.
427     * The value returned is identical to what would be returned by:
428     * <pre>
429     *    Byte.valueOf(x).compareTo(Byte.valueOf(y))
430     * </pre>
431     *
432     * @param  x the first {@code byte} to compare
433     * @param  y the second {@code byte} to compare
434     * @return the value {@code 0} if {@code x == y};
435     *         a value less than {@code 0} if {@code x < y}; and
436     *         a value greater than {@code 0} if {@code x > y}
437     * @since 1.7
438     */
439    public static int compare(byte x, byte y) {
440        return x - y;
441    }
442
443    /**
444     * The number of bits used to represent a {@code byte} value in two's
445     * complement binary form.
446     *
447     * @since 1.5
448     */
449    public static final int SIZE = 8;
450
451    /** use serialVersionUID from JDK 1.1. for interoperability */
452    private static final long serialVersionUID = -7183698231559129828L;
453
454    /** ----- BEGIN android -----
455     * @hide
456     */
457    public static String toHexString(byte b, boolean upperCase) {
458        char[] digits = upperCase ? UPPER_CASE_DIGITS : DIGITS;
459        char[] buf = new char[2]; // We always want two digits.
460        buf[0] = digits[(b >> 4) & 0xf];
461        buf[1] = digits[b & 0xf];
462        return new String(0, 2, buf);
463    }
464    private static final char[] DIGITS = {
465        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
466        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
467        'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
468        'u', 'v', 'w', 'x', 'y', 'z'
469    };
470
471    private static final char[] UPPER_CASE_DIGITS = {
472        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
473        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
474        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
475        'U', 'V', 'W', 'X', 'Y', 'Z'
476    };
477    // ----- END android -----
478}
479