Path: blob/master/src/java.base/share/classes/java/lang/Byte.java
41152 views
/*1* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.lang;2627import jdk.internal.misc.CDS;28import jdk.internal.vm.annotation.IntrinsicCandidate;2930import java.lang.constant.Constable;31import java.lang.constant.DynamicConstantDesc;32import java.util.Optional;3334import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;35import static java.lang.constant.ConstantDescs.CD_byte;36import static java.lang.constant.ConstantDescs.CD_int;37import static java.lang.constant.ConstantDescs.DEFAULT_NAME;3839/**40*41* The {@code Byte} class wraps a value of primitive type {@code byte}42* in an object. An object of type {@code Byte} contains a single43* field whose type is {@code byte}.44*45* <p>In addition, this class provides several methods for converting46* a {@code byte} to a {@code String} and a {@code String} to a {@code47* byte}, as well as other constants and methods useful when dealing48* with a {@code byte}.49*50* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>51* class; programmers should treat instances that are52* {@linkplain #equals(Object) equal} as interchangeable and should not53* use instances for synchronization, or unpredictable behavior may54* occur. For example, in a future release, synchronization may fail.55*56* @author Nakul Saraiya57* @author Joseph D. Darcy58* @see java.lang.Number59* @since 1.160*/61@jdk.internal.ValueBased62public final class Byte extends Number implements Comparable<Byte>, Constable {6364/**65* A constant holding the minimum value a {@code byte} can66* have, -2<sup>7</sup>.67*/68public static final byte MIN_VALUE = -128;6970/**71* A constant holding the maximum value a {@code byte} can72* have, 2<sup>7</sup>-1.73*/74public static final byte MAX_VALUE = 127;7576/**77* The {@code Class} instance representing the primitive type78* {@code byte}.79*/80@SuppressWarnings("unchecked")81public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");8283/**84* Returns a new {@code String} object representing the85* specified {@code byte}. The radix is assumed to be 10.86*87* @param b the {@code byte} to be converted88* @return the string representation of the specified {@code byte}89* @see java.lang.Integer#toString(int)90*/91public static String toString(byte b) {92return Integer.toString((int)b, 10);93}9495/**96* Returns an {@link Optional} containing the nominal descriptor for this97* instance.98*99* @return an {@link Optional} describing the {@linkplain Byte} instance100* @since 15101*/102@Override103public Optional<DynamicConstantDesc<Byte>> describeConstable() {104return Optional.of(DynamicConstantDesc.ofNamed(BSM_EXPLICIT_CAST, DEFAULT_NAME, CD_byte, intValue()));105}106107private static class ByteCache {108private ByteCache() {}109110static final Byte[] cache;111static Byte[] archivedCache;112113static {114final int size = -(-128) + 127 + 1;115116// Load and use the archived cache if it exists117CDS.initializeFromArchive(ByteCache.class);118if (archivedCache == null || archivedCache.length != size) {119Byte[] c = new Byte[size];120byte value = (byte)-128;121for(int i = 0; i < size; i++) {122c[i] = new Byte(value++);123}124archivedCache = c;125}126cache = archivedCache;127}128}129130/**131* Returns a {@code Byte} instance representing the specified132* {@code byte} value.133* If a new {@code Byte} instance is not required, this method134* should generally be used in preference to the constructor135* {@link #Byte(byte)}, as this method is likely to yield136* significantly better space and time performance since137* all byte values are cached.138*139* @param b a byte value.140* @return a {@code Byte} instance representing {@code b}.141* @since 1.5142*/143@IntrinsicCandidate144public static Byte valueOf(byte b) {145final int offset = 128;146return ByteCache.cache[(int)b + offset];147}148149/**150* Parses the string argument as a signed {@code byte} in the151* radix specified by the second argument. The characters in the152* string must all be digits, of the specified radix (as153* determined by whether {@link java.lang.Character#digit(char,154* int)} returns a nonnegative value) except that the first155* character may be an ASCII minus sign {@code '-'}156* ({@code '\u005Cu002D'}) to indicate a negative value or an157* ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to158* indicate a positive value. The resulting {@code byte} value is159* returned.160*161* <p>An exception of type {@code NumberFormatException} is162* thrown if any of the following situations occurs:163* <ul>164* <li> The first argument is {@code null} or is a string of165* length zero.166*167* <li> The radix is either smaller than {@link168* java.lang.Character#MIN_RADIX} or larger than {@link169* java.lang.Character#MAX_RADIX}.170*171* <li> Any character of the string is not a digit of the172* specified radix, except that the first character may be a minus173* sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign174* {@code '+'} ({@code '\u005Cu002B'}) provided that the175* string is longer than length 1.176*177* <li> The value represented by the string is not a value of type178* {@code byte}.179* </ul>180*181* @param s the {@code String} containing the182* {@code byte}183* representation to be parsed184* @param radix the radix to be used while parsing {@code s}185* @return the {@code byte} value represented by the string186* argument in the specified radix187* @throws NumberFormatException If the string does188* not contain a parsable {@code byte}.189*/190public static byte parseByte(String s, int radix)191throws NumberFormatException {192int i = Integer.parseInt(s, radix);193if (i < MIN_VALUE || i > MAX_VALUE)194throw new NumberFormatException(195"Value out of range. Value:\"" + s + "\" Radix:" + radix);196return (byte)i;197}198199/**200* Parses the string argument as a signed decimal {@code201* byte}. The characters in the string must all be decimal digits,202* except that the first character may be an ASCII minus sign203* {@code '-'} ({@code '\u005Cu002D'}) to indicate a negative204* value or an ASCII plus sign {@code '+'}205* ({@code '\u005Cu002B'}) to indicate a positive value. The206* resulting {@code byte} value is returned, exactly as if the207* argument and the radix 10 were given as arguments to the {@link208* #parseByte(java.lang.String, int)} method.209*210* @param s a {@code String} containing the211* {@code byte} representation to be parsed212* @return the {@code byte} value represented by the213* argument in decimal214* @throws NumberFormatException if the string does not215* contain a parsable {@code byte}.216*/217public static byte parseByte(String s) throws NumberFormatException {218return parseByte(s, 10);219}220221/**222* Returns a {@code Byte} object holding the value223* extracted from the specified {@code String} when parsed224* with the radix given by the second argument. The first argument225* is interpreted as representing a signed {@code byte} in226* the radix specified by the second argument, exactly as if the227* argument were given to the {@link #parseByte(java.lang.String,228* int)} method. The result is a {@code Byte} object that229* represents the {@code byte} value specified by the string.230*231* <p> In other words, this method returns a {@code Byte} object232* equal to the value of:233*234* <blockquote>235* {@code new Byte(Byte.parseByte(s, radix))}236* </blockquote>237*238* @param s the string to be parsed239* @param radix the radix to be used in interpreting {@code s}240* @return a {@code Byte} object holding the value241* represented by the string argument in the242* specified radix.243* @throws NumberFormatException If the {@code String} does244* not contain a parsable {@code byte}.245*/246public static Byte valueOf(String s, int radix)247throws NumberFormatException {248return valueOf(parseByte(s, radix));249}250251/**252* Returns a {@code Byte} object holding the value253* given by the specified {@code String}. The argument is254* interpreted as representing a signed decimal {@code byte},255* exactly as if the argument were given to the {@link256* #parseByte(java.lang.String)} method. The result is a257* {@code Byte} object that represents the {@code byte}258* value specified by the string.259*260* <p> In other words, this method returns a {@code Byte} object261* equal to the value of:262*263* <blockquote>264* {@code new Byte(Byte.parseByte(s))}265* </blockquote>266*267* @param s the string to be parsed268* @return a {@code Byte} object holding the value269* represented by the string argument270* @throws NumberFormatException If the {@code String} does271* not contain a parsable {@code byte}.272*/273public static Byte valueOf(String s) throws NumberFormatException {274return valueOf(s, 10);275}276277/**278* Decodes a {@code String} into a {@code Byte}.279* Accepts decimal, hexadecimal, and octal numbers given by280* the following grammar:281*282* <blockquote>283* <dl>284* <dt><i>DecodableString:</i>285* <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>286* <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>287* <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>288* <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>289* <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>290*291* <dt><i>Sign:</i>292* <dd>{@code -}293* <dd>{@code +}294* </dl>295* </blockquote>296*297* <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>298* are as defined in section {@jls 3.10.1} of299* <cite>The Java Language Specification</cite>,300* except that underscores are not accepted between digits.301*302* <p>The sequence of characters following an optional303* sign and/or radix specifier ("{@code 0x}", "{@code 0X}",304* "{@code #}", or leading zero) is parsed as by the {@code305* Byte.parseByte} method with the indicated radix (10, 16, or 8).306* This sequence of characters must represent a positive value or307* a {@link NumberFormatException} will be thrown. The result is308* negated if first character of the specified {@code String} is309* the minus sign. No whitespace characters are permitted in the310* {@code String}.311*312* @param nm the {@code String} to decode.313* @return a {@code Byte} object holding the {@code byte}314* value represented by {@code nm}315* @throws NumberFormatException if the {@code String} does not316* contain a parsable {@code byte}.317* @see java.lang.Byte#parseByte(java.lang.String, int)318*/319public static Byte decode(String nm) throws NumberFormatException {320int i = Integer.decode(nm);321if (i < MIN_VALUE || i > MAX_VALUE)322throw new NumberFormatException(323"Value " + i + " out of range from input " + nm);324return valueOf((byte)i);325}326327/**328* The value of the {@code Byte}.329*330* @serial331*/332private final byte value;333334/**335* Constructs a newly allocated {@code Byte} object that336* represents the specified {@code byte} value.337*338* @param value the value to be represented by the339* {@code Byte}.340*341* @deprecated342* It is rarely appropriate to use this constructor. The static factory343* {@link #valueOf(byte)} is generally a better choice, as it is344* likely to yield significantly better space and time performance.345*/346@Deprecated(since="9", forRemoval = true)347public Byte(byte value) {348this.value = value;349}350351/**352* Constructs a newly allocated {@code Byte} object that353* represents the {@code byte} value indicated by the354* {@code String} parameter. The string is converted to a355* {@code byte} value in exactly the manner used by the356* {@code parseByte} method for radix 10.357*358* @param s the {@code String} to be converted to a359* {@code Byte}360* @throws NumberFormatException if the {@code String}361* does not contain a parsable {@code byte}.362*363* @deprecated364* It is rarely appropriate to use this constructor.365* Use {@link #parseByte(String)} to convert a string to a366* {@code byte} primitive, or use {@link #valueOf(String)}367* to convert a string to a {@code Byte} object.368*/369@Deprecated(since="9", forRemoval = true)370public Byte(String s) throws NumberFormatException {371this.value = parseByte(s, 10);372}373374/**375* Returns the value of this {@code Byte} as a376* {@code byte}.377*/378@IntrinsicCandidate379public byte byteValue() {380return value;381}382383/**384* Returns the value of this {@code Byte} as a {@code short} after385* a widening primitive conversion.386* @jls 5.1.2 Widening Primitive Conversion387*/388public short shortValue() {389return (short)value;390}391392/**393* Returns the value of this {@code Byte} as an {@code int} after394* a widening primitive conversion.395* @jls 5.1.2 Widening Primitive Conversion396*/397public int intValue() {398return (int)value;399}400401/**402* Returns the value of this {@code Byte} as a {@code long} after403* a widening primitive conversion.404* @jls 5.1.2 Widening Primitive Conversion405*/406public long longValue() {407return (long)value;408}409410/**411* Returns the value of this {@code Byte} as a {@code float} after412* a widening primitive conversion.413* @jls 5.1.2 Widening Primitive Conversion414*/415public float floatValue() {416return (float)value;417}418419/**420* Returns the value of this {@code Byte} as a {@code double}421* after a widening primitive conversion.422* @jls 5.1.2 Widening Primitive Conversion423*/424public double doubleValue() {425return (double)value;426}427428/**429* Returns a {@code String} object representing this430* {@code Byte}'s value. The value is converted to signed431* decimal representation and returned as a string, exactly as if432* the {@code byte} value were given as an argument to the433* {@link java.lang.Byte#toString(byte)} method.434*435* @return a string representation of the value of this object in436* base 10.437*/438public String toString() {439return Integer.toString((int)value);440}441442/**443* Returns a hash code for this {@code Byte}; equal to the result444* of invoking {@code intValue()}.445*446* @return a hash code value for this {@code Byte}447*/448@Override449public int hashCode() {450return Byte.hashCode(value);451}452453/**454* Returns a hash code for a {@code byte} value; compatible with455* {@code Byte.hashCode()}.456*457* @param value the value to hash458* @return a hash code value for a {@code byte} value.459* @since 1.8460*/461public static int hashCode(byte value) {462return (int)value;463}464465/**466* Compares this object to the specified object. The result is467* {@code true} if and only if the argument is not468* {@code null} and is a {@code Byte} object that469* contains the same {@code byte} value as this object.470*471* @param obj the object to compare with472* @return {@code true} if the objects are the same;473* {@code false} otherwise.474*/475public boolean equals(Object obj) {476if (obj instanceof Byte) {477return value == ((Byte)obj).byteValue();478}479return false;480}481482/**483* Compares two {@code Byte} objects numerically.484*485* @param anotherByte the {@code Byte} to be compared.486* @return the value {@code 0} if this {@code Byte} is487* equal to the argument {@code Byte}; a value less than488* {@code 0} if this {@code Byte} is numerically less489* than the argument {@code Byte}; and a value greater than490* {@code 0} if this {@code Byte} is numerically491* greater than the argument {@code Byte} (signed492* comparison).493* @since 1.2494*/495public int compareTo(Byte anotherByte) {496return compare(this.value, anotherByte.value);497}498499/**500* Compares two {@code byte} values numerically.501* The value returned is identical to what would be returned by:502* <pre>503* Byte.valueOf(x).compareTo(Byte.valueOf(y))504* </pre>505*506* @param x the first {@code byte} to compare507* @param y the second {@code byte} to compare508* @return the value {@code 0} if {@code x == y};509* a value less than {@code 0} if {@code x < y}; and510* a value greater than {@code 0} if {@code x > y}511* @since 1.7512*/513public static int compare(byte x, byte y) {514return x - y;515}516517/**518* Compares two {@code byte} values numerically treating the values519* as unsigned.520*521* @param x the first {@code byte} to compare522* @param y the second {@code byte} to compare523* @return the value {@code 0} if {@code x == y}; a value less524* than {@code 0} if {@code x < y} as unsigned values; and525* a value greater than {@code 0} if {@code x > y} as526* unsigned values527* @since 9528*/529public static int compareUnsigned(byte x, byte y) {530return Byte.toUnsignedInt(x) - Byte.toUnsignedInt(y);531}532533/**534* Converts the argument to an {@code int} by an unsigned535* conversion. In an unsigned conversion to an {@code int}, the536* high-order 24 bits of the {@code int} are zero and the537* low-order 8 bits are equal to the bits of the {@code byte} argument.538*539* Consequently, zero and positive {@code byte} values are mapped540* to a numerically equal {@code int} value and negative {@code541* byte} values are mapped to an {@code int} value equal to the542* input plus 2<sup>8</sup>.543*544* @param x the value to convert to an unsigned {@code int}545* @return the argument converted to {@code int} by an unsigned546* conversion547* @since 1.8548*/549public static int toUnsignedInt(byte x) {550return ((int) x) & 0xff;551}552553/**554* Converts the argument to a {@code long} by an unsigned555* conversion. In an unsigned conversion to a {@code long}, the556* high-order 56 bits of the {@code long} are zero and the557* low-order 8 bits are equal to the bits of the {@code byte} argument.558*559* Consequently, zero and positive {@code byte} values are mapped560* to a numerically equal {@code long} value and negative {@code561* byte} values are mapped to a {@code long} value equal to the562* input plus 2<sup>8</sup>.563*564* @param x the value to convert to an unsigned {@code long}565* @return the argument converted to {@code long} by an unsigned566* conversion567* @since 1.8568*/569public static long toUnsignedLong(byte x) {570return ((long) x) & 0xffL;571}572573574/**575* The number of bits used to represent a {@code byte} value in two's576* complement binary form.577*578* @since 1.5579*/580public static final int SIZE = 8;581582/**583* The number of bytes used to represent a {@code byte} value in two's584* complement binary form.585*586* @since 1.8587*/588public static final int BYTES = SIZE / Byte.SIZE;589590/** use serialVersionUID from JDK 1.1. for interoperability */591@java.io.Serial592private static final long serialVersionUID = -7183698231559129828L;593}594595596