< prev index next >

src/java.base/share/classes/java/lang/Byte.java

Print this page

  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.AOTSafeClassInitializer;
 30 import jdk.internal.vm.annotation.IntrinsicCandidate;
 31 import jdk.internal.vm.annotation.Stable;
 32 
 33 import java.lang.constant.Constable;
 34 import java.lang.constant.DynamicConstantDesc;
 35 import java.util.Optional;
 36 
 37 import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;
 38 import static java.lang.constant.ConstantDescs.CD_byte;
 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");

 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     @AOTSafeClassInitializer
107     private static final class ByteCache {
108         private ByteCache() {}
109 
110         @Stable
111         static final Byte[] cache;
112         static Byte[] archivedCache;
113 
114         static {
115             final int size = -(-128) + 127 + 1;
116 
117             // Load and use the archived cache if it exists
118             CDS.initializeFromArchive(ByteCache.class);
119             if (archivedCache == null) {
120                 Byte[] c = new Byte[size];
121                 byte value = (byte)-128;
122                 for(int i = 0; i < size; i++) {
123                     c[i] = new Byte(value++);



124                 }
125                 archivedCache = c;




126             }
127             cache = archivedCache;
128             assert cache.length == size;
129         }
130     }
131 
132     /**
133      * Returns a {@code Byte} instance representing the specified
134      * {@code byte} value.
135      * If a new {@code Byte} instance is not required, this method
136      * should generally be used in preference to the constructor
137      * {@link #Byte(byte)}, as this method is likely to yield
138      * significantly better space and time performance since
139      * all byte values are cached.












140      *
141      * @param  b a byte value.
142      * @return a {@code Byte} instance representing {@code b}.
143      * @since  1.5
144      */
145     @IntrinsicCandidate

146     public static Byte valueOf(byte b) {
147         final int offset = 128;
148         return ByteCache.cache[(int)b + offset];



149     }
150 
151     /**
152      * Parses the string argument as a signed {@code byte} in the
153      * radix specified by the second argument. The characters in the
154      * string must all be digits, of the specified radix (as
155      * determined by whether {@link java.lang.Character#digit(char,
156      * int)} returns a nonnegative value) except that the first
157      * character may be an ASCII minus sign {@code '-'}
158      * ({@code '\u005Cu002D'}) to indicate a negative value or an
159      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
160      * indicate a positive value.  The resulting {@code byte} value is
161      * returned.
162      *
163      * <p>An exception of type {@code NumberFormatException} is
164      * thrown if any of the following situations occurs:
165      * <ul>
166      * <li> The first argument is {@code null} or is a string of
167      * length zero.
168      *

  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");

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      *
< prev index next >