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