Home Java javaTutorial Detailed analysis of the source code of Byte class in Java--step details

Detailed analysis of the source code of Byte class in Java--step details

Aug 04, 2018 am 11:36 AM

Today, let’s analyze the source code of the java.lang.Byte class and go straight to the topic

First of all

public final class Byte extends Number implements Comparable<Byte> {
public static final byte   MIN_VALUE = -128;
public static final byte   MAX_VALUE = 127;
public static final int SIZE = 8;
public static final int BYTES = SIZE / Byte.SIZE;
    @SuppressWarnings("unchecked")
    public static final Class<Byte>     TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
Copy after login

The first sentence of the Byte class is modified by final and cannot be inherited. Inherit The Number class can be used for a series of conversions of numeric types. It implements the Comparable interface, which can be used for comparison.
The second and third sentences define the minimum and maximum values.
The fourth sentence defines the size of Byte. , is 8 bits, that is, one byte
The fifth sentence gives the byte, that is, SIZE/Byte.SIZE = 1; occupies one byte
The sentence that is annotated to remain silent for warnings is Get the two constructors of the original class

    public Byte(byte value) {
        this.value = value;
    }
    public Byte(String s) throws NumberFormatException {
        this.value = parseByte(s, 10);
    }
Copy after login

Byte class. There are restrictions here. The value passed in must be a byte type value, and the string s must be a string that can be converted to a number. Otherwise, An error will be reported

    public static String toString(byte b) {
        return Integer.toString((int)b, 10);
    }
    public String toString() {
        return Integer.toString((int)value);
    }
    private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }
Copy after login
  • Next is the toString method, which converts the byte type into a string, which uses the method in the Integer class

The following The ByteCache method defines a Byte cache value and writes -128~127 into a cache array. When it is within this range, the JVM will directly use the cache value, but when it exceeds this range, overflow will occur. As mentioned in the previous article, 128 will become -128, and the loop calculation will continue from the minimum value

parseByte parses the string type into byte type, radix is ​​the base, radix is ​​the number, and s is A decimal number. The result after parsing is a decimal number.

    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    public static Byte valueOf(String s, int radix)
        throws NumberFormatException {
        return valueOf(parseByte(s, radix));
    }
    public static Byte valueOf(String s) throws NumberFormatException {
        return valueOf(s, 10);
    }
Copy after login

Convert the value of the incoming parameter to the Byte type. Here it is taken directly from the cache. The method of hanging the parameter radix is ​​to first parse the string into decimal. Then perform valueOf

    public static Byte decode(String nm) throws NumberFormatException {
        int i = Integer.decode(nm);
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                    "Value " + i + " out of range from input " + nm);
        return valueOf((byte)i);
    }
Copy after login

This is a decoding and transcoding method. The previous method was not written like this. Now the decode method of the Integer class is directly called, and then it is judged whether it is less than the minimum value or greater than the maximum value. Then convert it to the byte type and return it. Now it really answers the sentence "There is no byte type in Java"

    public byte byteValue() {
        return value;
    }
    public short shortValue() {
        return (short)value;
    }
    public int intValue() {
        return (int)value;
    }
    public long longValue() {
        return (long)value;
    }
    public float floatValue() {
        return (float)value;
    }
    public double doubleValue() {
        return (double)value;
    }
Copy after login

These are some methods of forced type conversion, which are very simple, but still write

    @Override
    public int hashCode() {
        return Byte.hashCode(value);
    }
    public static int hashCode(byte value) {
        return (int)value;
    }
Copy after login

The first hashCode is an override of the hasnCode method of Object, which is used to compare two values. The hashCode method is often distinguished from the equals method, especially during interviews. This will not be explained in detail now. The hashCode method is mostly used in the

    public boolean equals(Object obj) {
        if (obj instanceof Byte) {
            return value == ((Byte)obj).byteValue();
        }
        return false;
    }
Copy after login

equals method of the collection. Now it is worth comparing.

    public int compareTo(Byte anotherByte) {
        return compare(this.value, anotherByte.value);
    }
    public static int compare(byte x, byte y) {
        return x - y;
    }
Copy after login

Comparison method, if x > y, returns a positive number, if x = y, returns 0. If x < y, return a negative number

    public static int toUnsignedInt(byte x) {
        return ((int) x) & 0xff;
    }
    public static long toUnsignedLong(byte x) {
        return ((long) x) & 0xffL;
    }
Copy after login

Convert byte type to unsigned int type and long type

private static final long serialVersionUID = -7183698231559129828L;
Copy after login
  • Used during serialization, now Without further explanation, I don’t quite understand the serialization process. . . .

Related articles:

java int to byte and long to byte

Analysis of Buffer source code in java

The above is the detailed content of Detailed analysis of the source code of Byte class in Java--step details. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles