[Java source code] Byte

This time we take a look at Bytethe class source code, based on jdk1.8.0_181.jdk version.

Overview

The Java Byteclass mainly on byteencapsulation of basic data types, with one field corresponding to the stored bytedata value, the method additionally provides some convenience to byteperform related operations.

Class definition

public final class Byte extends Number implements Comparable<Byte>
复制代码

ByteClass with the keyword final, which is not inherited , in addition to inheriting the Numberclass that implements Comparablethe interface, that is, can be compared.

Attributes

public static final byte   MIN_VALUE = -128;

public static final byte   MAX_VALUE = 127;
复制代码

Define the Bytesize range because of complement, negative numbers positive number one more than required, it MIN_VALUEcan take on the values -2**8, and MAX_VALUEcan take the value 2**8 - 1, the logic specific and complement codes, can refer to the original code, anti-code, produced complement, applications, and what the advantages and disadvantages? - know almost user's answer - know almost , to explain personally feel good.

public static final int SIZE = 8;
复制代码

It defines the bytetwo's complement format value bitbits, 8 is fixed.

public static final int BYTES = SIZE / Byte.SIZE;
复制代码

Defines the bytenumber of bytes in twos complement format, the value, calculated value is fixed.

@SuppressWarnings("unchecked")
public static final Class<Byte>     TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
复制代码

Acquiring Bytecategory information Byte.TYPE == byte.class, they are equivalent.

private final byte value;
复制代码

ByteBecause bytethe packaging, so here it contains the corresponding bytevariable of the basic types of data.

private static final long serialVersionUID = -7183698231559129828L;
复制代码

Inner classes

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));
  }
}
复制代码

This defines a static nested class defines an internal array of size -(-128)+127+1=256, comprising the values between -128 and 127. Static blocks initialized array of values. Add here a knowledge point, Java class loading sequence, 静态变量/代码块 -> 非静态变量/代码块 -> 构造方法the same part of which is loaded in accordance with the order of the code, detailed contents can search for their own learning.

About instructions within the class, you can refer to the official documentation Nested Classes for further understanding of learning.

method

Construction method

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

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

复制代码

The presence of two corresponding construction method, an incoming bytevalue, a is an incoming string parsing, converted to decimal integer processing (Note that this method may throw an exception, it is noted process), corresponding to the following analytical methods introduction.

parseByte 方法

public static byte parseByte(String s, int radix)
  throws NumberFormatException {
  int i = Integer.parseInt(s, radix);
  if (i < MIN_VALUE || i > MAX_VALUE)
    throw new NumberFormatException(
    "Value out of range. Value:\"" + s + "\" Radix:" + radix);
  return (byte)i;
}

复制代码

Incoming string and hexadecimal number, call the Integer.parseIntmethod to get the converted integer, integer to determine whether the scope Byterange. If so, cast bytethe return type; not, throw an NumberFormatExceptionexception.

public static byte parseByte(String s) throws NumberFormatException {
  return parseByte(s, 10);
}

复制代码

The presence of a one-parameter parseBytemethod, the above method is implemented by calling the default number of decimal 10.

toString method

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

public String toString() {
  return Integer.toString((int)value);
}

复制代码

The direct bytetype value into the cast int, and then call a Integer.toStringmethod of operation.

valueOf Method

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

复制代码

For bytetype parameter, directly calculate the offset, reads the ByteCachestatic variable corresponding to the value of the array to operate within the class to improve the performance of the corresponding space and time.

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

复制代码

These two methods are for the stringtype of the parameter, the problem is only set hex. Used parseBytemethod to convert the string to a bytetype value, and then directly use the first valueOfmethod of operation.

decode method

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

复制代码

For decoding the string, converts the string to a Bytetype value. The main logic calls the Integer.decodemethod to obtain a digital decoded, and then determines whether the return to the corresponding byterequirements, the call valueOfreturns the final result.

Removing +/-symbols, will be decoded according to the specific situation, the default will be treated as a decimal. 0x,0X,#Will be treated as the beginning of the hex, 0the beginning will be treated as octal.

xxxValue method

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

复制代码

By casts, expanding the scope of the original value types, returns the result.

hashCode method

@Override
public int hashCode() {
  return Byte.hashCode(value);
}

public static int hashCode(byte value) {
  return (int)value;
}

复制代码

Return directly corresponding to intthe type of value, as hashCode.

equals method

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

复制代码

First, obj is not determined parameters passed Byteinstance, is the case of the comparative values of both are equal; otherwise, return directly false. Can be seen from here, we do not need to pass parameters in the use of null == objjudgment and can be ignored.

compare method

public static int compare(byte x, byte y) {
  return x - y;
}

复制代码

Comparing both values, when x is less than y returns negative, returns 0 when x is equal to y, returns a positive number when x is greater than y.

compareTo method

public int compareTo(Byte anotherByte) {
  return compare(this.value, anotherByte.value);
}

复制代码

Internal call comparemethod.

toUnsignedInt method

public static int toUnsignedInt(byte x) {
  return ((int) x) & 0xff;
}

复制代码

The byteconverted unsigned integer. x cast to inttype value, by 0xffthe bitwise operation, preserving low 8-bit value, the upper 24 bits set to zero. The overall result, the number 0 and n remain the same, a negative value is equal to the original 8 + 2 **.

toUnsignedLong method

public static long toUnsignedLong(byte x) {
  return ((long) x) & 0xffL;
}

复制代码

Procedure is as above, only long64 bits, the lower 8 bits is asserted, the high 56 set to 0.

to sum up

Found by reading the source code, Bytethe class of the extensive use Integerof the method, the additional use of an internal class, bit operations, etc. for a certain amount of logic optimization. In the process of looking for their own load order inner classes, complement, also learned more about the class, continue to fuel!

At last

Address correspondence blog: blog.renyijiu.com/post/java source ...

Guess you like

Origin juejin.im/post/5d63b521f265da03b638b99f