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