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