Java – byte constructor and byte Differences between valueof () methods

Byte byte1=new Byte("10");
Byte byte1=new Byte("10");
Byte byte2=Byte.valueOf("10");

System.out.println(byte1);
System.out.println(byte2);

Byte1 and byte2 both print the same value 10 Then, what is the difference between the byte and valueof () methods parameterized by the constructor

Solution

The byte class source code in JDK 7 shows this:

(I chose the byte version instead of the string version because there is less code, but the idea is exactly the same)

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

And:

public Byte(byte value) 
{
   this.value = value;
}

The location of bytecache is:

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

Basically, the constructor version is used to create a completely new version, while the valueof version returns a pre - existing version This saves memory because byte Valueof (10) has only one value, no matter how many times you call it, but if you execute a new byte (10), a new value will be created for each call to new Since bytes are immutable (they have no mutable state), there is no reason to create multiple bytes for any given value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>