Java basic data types and package types

Foreword

There are many aspects of the Java basic, basic data types and package types considered one, we have to grasp.

First, the basic data types

In Java, the basic data types can be divided into the following categories:

  • Numeric
    • Integer type
      • byte
      • short
      • int
      • long
    • Floating-point type
      • float
      • double
  • Character
    • char
  • Boolean
    • boolean

And in turn uses three decimal integer type to represent.

  1. Decimal (default)
  2. Octal (beginning with 0)
  3. Hexadecimal (beginning with 0x or 0X)

FIG integer type and amount of memory ranges are as follows. The default integer type int, if you want to use long, the need to add a lowercase or uppercase l L at the end, a recommended use upper L, to avoid their uppercase letter i and I confusion.

Integer type RAM Ranges
byte 8 bit -128 - 127
short 16 bit -32768 - 32767
int 32 bit -2^32 - 2^32-1
long 64 bit -2^32 - 2^32-1

For floating-point type, default doubletype, if you want to use float, the need to add value at the end of uppercase or lowercase f F, recommend the use of uppercase F.

Only one type of boolean, false is represented by 0, true represented by 1.

char type is used to represent all unicode characters in the table, unicode table covering almost all the characters in all countries in all languages. The range of 0 - 65535. char string as constituent units, plays an important role.

In essence, is a value char, unicode indicates the position of the table, for example, the following two statements are actually equivalent.

char ch = 'a';
char ch = 97;

Further, in the case where the value does not cross the border, char and int can be automatically converted.

char word = 'd';
int p = 23045;
System.out.println("word is " + (int)word);
System.out.println("p is " + (char)p);

Java has some turned from characters have special meanings, for example:

  1. \' -- apostrophe
  2. \\ - backslash
  3. \ T - tabbing
  4. \ R - carriage return
  5. \ N - newline
  6. \ B - Backspace
  7. \ F - feed

Second, the type of packaging

We mentioned above eight kinds of basic data types, each data type and corresponding to a package type, as follows:

Basic data types type of packaging
boolean Boolean
char Character
int Integer
byte Byte
short Short
long Long
float Float
double Double

Why do we need the basic data types?

For efficiency. Create new objects stored in the heap, simple little use if the variable objects created, and efficiency is not high. Therefore, these variables are stored directly in the stack area, resulting in improved efficiency.

Why do we need the type of package?

  1. Basic types do not have the properties of an object, such as a property and a method. Packaging type is to allow basic types of objects have properties;
  2. You can easily use generics. For example, we can not directly into a collection of basic data type classes.

In order to flexibly support package type, Java compiler provides a mechanism for automatic boxing and unboxing. E.g:

Integer x = new Integer(36);
int y = x;
int z = 36;
Integer u = new Integer(z);

Basic types and package types there are some differences, mainly reflected in the following points:

  1. Basic types can not use the new keyword to create, package type must be created using the new keyword.
  2. Stored in different locations. The basic types are stored in the stack area, the type of packaging is stored in the stack area.
  3. Different initial values. Basic types int initial value 0, boolean initial value is false. Package Type initial values ​​are null. Therefore, when performing unpacking autoloader must avoid null pointer exception.
  4. Different usage scenarios. The basic calculation and assignment type is mainly used. Type of packaging for generics.
  5. The basic types are passed by value, type of packaging is passed by reference.

[Note]: should be avoided xxx == yyyand xxx.equals(yyy)a way to compare, but rather by Objects.equals(xxx, yyy)the way.

Third, the packaging method of the type commonly

1. Boolean

public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
public static final Class<Boolean> TYPE = (Class<Boolean>) Class.getPrimitiveClass("boolean");
public Boolean(boolean value) {
    this.value = value;
}
public Boolean(String s) {
    this(parseBoolean(s));
}
public static boolean parseBoolean(String s) {
    return ((s != null) && s.equalsIgnoreCase("true"));
}
public boolean booleanValue() {
    return value;
}
public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}
public static Boolean valueOf(String s) {
    return parseBoolean(s) ? TRUE : FALSE;
}
public static String toString(boolean b) {
    return b ? "true" : "false";
}
public String toString() {
    return value ? "true" : "false";
}
public static boolean parseBoolean(String s) {
    return ((s != null) && s.equalsIgnoreCase("true"));
}

2. Integer

public static final int MIN_VALUE = 0x80000000;
public static final int MAX_VALUE = 0x7fffffff;
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
public static Integer valueOf(String s);
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
public int intValue();
public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
}

3. Long

public static final long MIN_VALUE = 0x8000000000000000L;
public static final long MAX_VALUE = 0x7fffffffffffffffL;
public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long");
public static Long valueOf(String s);
public static Long valueOf(long l) {
    final int offset = 128;
    if (l >= -128 && l <= 127) { // will cache
        return LongCache.cache[(int)l + offset];
    }
    return new Long(l);
}
public long longValue();
public static long parseLong(String s) throws NumberFormatException {
    return parseLong(s, 10);
}

4. Double

/**
 * 用于表示正无穷大
 * A constant holding the positive infinity of type
 * {@code double}. It is equal to the value returned by
 * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
 */
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

/**
 * 用于表示负无穷大
 * A constant holding the negative infinity of type
 * {@code double}. It is equal to the value returned by
 * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
 */
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

/**
 * 用于表示非数字
 * A constant holding a Not-a-Number (NaN) value of type
 * {@code double}. It is equivalent to the value returned by
 * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
 */
public static final double NaN = 0.0d / 0.0;

/**
 * 最大值
 * A constant holding the largest positive finite value of type
 * {@code double},
 * (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>.  It is equal to
 * the hexadecimal floating-point literal
 * {@code 0x1.fffffffffffffP+1023} and also equal to
 * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
 */
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308

/**
 * 最小的正值
 * A constant holding the smallest positive normal value of type
 * {@code double}, 2<sup>-1022</sup>.  It is equal to the
 * hexadecimal floating-point literal {@code 0x1.0p-1022} and also
 * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.
 *
 * @since 1.6
 */
public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308

/**
 * 最小值
 * A constant holding the smallest positive nonzero value of type
 * {@code double}, 2<sup>-1074</sup>. It is equal to the
 * hexadecimal floating-point literal
 * {@code 0x0.0000000000001P-1022} and also equal to
 * {@code Double.longBitsToDouble(0x1L)}.
 */
public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324

/**
 * 最大的指数
 * Maximum exponent a finite {@code double} variable may have.
 * It is equal to the value returned by
 * {@code Math.getExponent(Double.MAX_VALUE)}.
 *
 * @since 1.6
 */
public static final int MAX_EXPONENT = 1023;

/**
 * 最小的指数
 * Minimum exponent a normalized {@code double} variable may
 * have.  It is equal to the value returned by
 * {@code Math.getExponent(Double.MIN_NORMAL)}.
 *
 * @since 1.6
 */
public static final int MIN_EXPONENT = -1022;

/**
 * double的长度
 * The number of bits used to represent a {@code double} value.
 *
 * @since 1.5
 */
public static final int SIZE = 64;

/**
 * double占用的字节数
 * The number of bytes used to represent a {@code double} value.
 *
 * @since 1.8
 */
public static final int BYTES = SIZE / Byte.SIZE;

/**
 * The {@code Class} instance representing the primitive type
 * {@code double}.
 *
 * @since JDK1.1
 */
@SuppressWarnings("unchecked")
public static final Class<Double>   TYPE = (Class<Double>) Class.getPrimitiveClass("double");
public static Double valueOf(String s);
public static Double valueOf(double d) {
    return new Double(d);
}
public double doubleValue() {
    return value;
}
public static double parseDouble(String s) throws NumberFormatException {
    return FloatingDecimal.parseDouble(s);
}

5. Float

/**
 * A constant holding the positive infinity of type
 * {@code float}. It is equal to the value returned by
 * {@code Float.intBitsToFloat(0x7f800000)}.
 */
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;

/**
 * A constant holding the negative infinity of type
 * {@code float}. It is equal to the value returned by
 * {@code Float.intBitsToFloat(0xff800000)}.
 */
public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;

/**
 * A constant holding a Not-a-Number (NaN) value of type
 * {@code float}.  It is equivalent to the value returned by
 * {@code Float.intBitsToFloat(0x7fc00000)}.
 */
public static final float NaN = 0.0f / 0.0f;

/**
 * A constant holding the largest positive finite value of type
 * {@code float}, (2-2<sup>-23</sup>)&middot;2<sup>127</sup>.
 * It is equal to the hexadecimal floating-point literal
 * {@code 0x1.fffffeP+127f} and also equal to
 * {@code Float.intBitsToFloat(0x7f7fffff)}.
 */
public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f

/**
 * A constant holding the smallest positive normal value of type
 * {@code float}, 2<sup>-126</sup>.  It is equal to the
 * hexadecimal floating-point literal {@code 0x1.0p-126f} and also
 * equal to {@code Float.intBitsToFloat(0x00800000)}.
 *
 * @since 1.6
 */
public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f

/**
 * A constant holding the smallest positive nonzero value of type
 * {@code float}, 2<sup>-149</sup>. It is equal to the
 * hexadecimal floating-point literal {@code 0x0.000002P-126f}
 * and also equal to {@code Float.intBitsToFloat(0x1)}.
 */
public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f

/**
 * Maximum exponent a finite {@code float} variable may have.  It
 * is equal to the value returned by {@code
 * Math.getExponent(Float.MAX_VALUE)}.
 *
 * @since 1.6
 */
public static final int MAX_EXPONENT = 127;

/**
 * Minimum exponent a normalized {@code float} variable may have.
 * It is equal to the value returned by {@code
 * Math.getExponent(Float.MIN_NORMAL)}.
 *
 * @since 1.6
 */
public static final int MIN_EXPONENT = -126;

/**
 * The number of bits used to represent a {@code float} value.
 *
 * @since 1.5
 */
public static final int SIZE = 32;

/**
 * The number of bytes used to represent a {@code float} value.
 *
 * @since 1.8
 */
public static final int BYTES = SIZE / Byte.SIZE;

/**
 * The {@code Class} instance representing the primitive type
 * {@code float}.
 *
 * @since JDK1.1
 */
@SuppressWarnings("unchecked")
public static final Class<Float> TYPE = (Class<Float>) Class.getPrimitiveClass("float");
public static Float valueOf(String s) throws NumberFormatException {
    return new Float(parseFloat(s));
}
public static Float valueOf(float f) {
    return new Float(f);
}
public static float parseFloat(String s) throws NumberFormatException {
    return FloatingDecimal.parseFloat(s);
}
public float floatValue() {
    return value;
}

6. Byte

public static final byte MIN_VALUE = -128;
public static final byte MAX_VALUE = 127;
public static final Class<Byte>     TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
public static Byte valueOf(byte b) {
    final int offset = 128;
    return ByteCache.cache[(int)b + offset];
}
public static byte parseByte(String s) throws NumberFormatException {
    return parseByte(s, 10);
}
public static Byte valueOf(String s) throws NumberFormatException {
    return valueOf(s, 10);
}
public byte byteValue() {
    return value;
}

7. Short

public static final short MIN_VALUE = -32768;
public static final short MAX_VALUE = 32767;
public static final Class<Short>    TYPE = (Class<Short>) Class.getPrimitiveClass("short");
public static short parseShort(String s) throws NumberFormatException {
    return parseShort(s, 10);
}
public static Short valueOf(String s) throws NumberFormatException {
    return valueOf(s, 10);
}
public static Short valueOf(short s) {
    final int offset = 128;
    int sAsInt = s;
    if (sAsInt >= -128 && sAsInt <= 127) { // must cache
        return ShortCache.cache[sAsInt + offset];
    }
    return new Short(s);
}
public short shortValue() {
    return value;
}

8. Character

public static final Class<Character> TYPE = (Class<Character>) Class.getPrimitiveClass("char");
public static Character valueOf(char c) {
    if (c <= 127) { // must cache
        return CharacterCache.cache[(int)c];
    }
    return new Character(c);
}
public char charValue() {
    return value;
}

9. A brief summary

By analyzing the common method, we see that all packaging types have a number of similar fields or functions, their main role is to simplify our basic types of treatment and type of packaging operations. The automatic boxing and unboxing is the more important of a mechanism.

Fourth, the principle of automatic boxing and unboxing

java To simplify the complexity of our use of the basic type and the type of packaging, boxing and unboxing expressly incorporated the mechanism.

  1. Packing Mechanism - converting the basic data types for the packaging type
  2. Unpacking Mechanism - converting the basic data type package type
public class Main {

    public static void main(String[] args) {
        Integer a = 32323;
        int b = a;
    }
}

The above code, we use javap -c to decompile it, see the following results:

C:\Users\Administrator>javap -c D:\zhangfb\ws\demo\target\classes\com\juconcurre
nt\demo\Main.class
Compiled from "Main.java"
public class com.juconcurrent.demo.Main {
  public com.juconcurrent.demo.Main();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":
()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: sipush        32323
       3: invokestatic  #2                  // Method java/lang/Integer.valueOf:
(I)Ljava/lang/Integer;
       6: astore_1
       7: aload_1
       8: invokevirtual #3                  // Method java/lang/Integer.intValue
:()I
      11: istore_2
      12: return
}

We saw #2and #3they correspond to is boxing and unboxing. In fact, boxing is to call a valueOf()method, and unpacking is called a intValue()method. Similarly, other types have the same mechanism.

to sum up

First, we introduce the basic types and package types, and then describes the similarities and differences between their role.
Then, to understand the type commonly used in packaging fields and functions, their names are very standard, achieve function is also very simple.
Finally, we adopted automatic boxing and unboxing mechanism, in which the analysis of these functions play a role.

reference

  1. https://www.cnblogs.com/huajiezh/p/5225637.html
  2. https://www.cnblogs.com/lxrm/p/6427628.html
  3. https://blog.csdn.net/johntang2014/article/details/83027553

Reproduced in: https: //www.jianshu.com/p/cc44e2fd5b3a

Guess you like

Origin blog.csdn.net/weixin_34175509/article/details/91068202