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