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