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