Complete understanding of the basic types of java data types and the concepts of reference types (collected online)

You have to settle down and read this article carefully . After reading this article in one day, I think you are making money all day.

1. First, the data types of java are classified as:

Everything should be an object in the java world. Why are there basic types?

(1) Due to performance issues, we have to use : Java based on performance considerations, the basic data types written in c , the basic data types are stored in the stack ( access speed is faster than the heap, second only to the registers directly located in the CPU ) speed ratio The heap storage is extremely fast, and the variables defined by the basic types are created and destroyed quickly, while the variables defined by the class need to be destroyed by the JVM.
(2) In order to meet java object-oriented : boxing and unboxing : the  packaging type wraps the value of the basic type in the object, so that you can use the method of the object to manipulate the basic type, and the conversion between types requires the use of the packaging type method It can be completed, so a packaging type is required.

Boxing : the process of converting basic types into packaging classes

Unboxing : the process of converting packaging classes into basic types

  (3) [The difference between object and basic data type]

Basic data types are allocated on the stack, and object types are allocated on the heap.

The parameters of all methods are passed by reference rather than their own value (except for basic types).

Assignment between objects is just to pass by reference, assignment between basic types is to create a new copy.

2. Eight basic types

The eight basic types in Java are: byte, short, int, long, float, double, char and boolean.

Let me start with the first question:

(1). Type conversion data overflow problem

First: 1 byte occupies 8 bits.

Divided into the following categories:

      Integer type: byte, short, int, long occupy 1, 2, 4, and 8 bytes of space respectively;

      Floating point type: long and float occupy 4 and 8 bytes respectively;

      Char type: char occupies 2 bytes;

      boolean type: boolean occupies 1 bit.

A concept needs to be interspersed among them: +++++++bytes and bits+++++++

Bit concept

In the binary number system, each 0 or 1 is a bit, and a bit is the smallest unit of data storage. Among them, 8bit is called a byte (Byte). The number of CPU bits in a computer refers to the maximum number of bits that the CPU can process at a time. For example, the CPU of a 32-bit computer can process up to 32 bits of data at a time.

Binary bits:

Binary bit is abbreviated as "bit", which is a symbol that represents an integer less than 2 in the binary number system. It is generally represented by 1 or 0, which is one of two states with equal probability.

The number of binary bits can represent the word length of a machine word, and the amount of information contained in a binary bit is called a bit

Bit (BIT, binary system):

Computer terminology is a unit of information, which is transliterated from English BIT. At the same time, it is also the bit in the binary number, the unit of measurement of the amount of information, and the smallest unit of the amount of information. Information necessary to reduce the number of alternative stimuli by half when different choices need to be made. That is, the amount of information (number of bits) of the signal is equal to the logarithm of the signal stimulus with 2 as the base. L. Hartley thought in 1928 that the logarithmic unit is the most appropriate measure for the amount of information. For example, the binary number 0100 is 4 bits.

Expansion issues:

(1). Why should one design 1 byte=8Bit?

The so-called byte, the original intent is used to represent a complete character. The initial computer performance and storage capacity were relatively poor, so 4-bit BCD encoding was generally used (this encoding appeared earlier than computers, and was first used on punch cards). The BCD code is okay to represent numbers, but it is not easy to represent letters or symbols, and multiple codes are needed to represent it. Later evolved the 6-bit BCD code (BCDIC), and the 7-bit ASCII code that is still widely used today. But it is the famous System/360 that determines the byte size in the end. At that time, IBM designed a set of 8-bit EBCDIC codes for System/360, which covered numbers, uppercase and lowercase letters and most common symbols, and was compatible with 6-bit BCDIC codes widely used in punch cards. System/360 was very successful and laid the foundation for the 8-bit length of the character storage unit. This is the origin of 1 byte = 8 bits.

Links to the following two questions: https://www.jianshu.com/p/d0a8ff006f5c

(2) We all know that the maximum value that a binary 8-bit can represent is 1111 1111 == 255, but why the maximum value is 127?

Because for computers, the highest bit of a binary number is the sign bit, with 0 representing a positive number and 1 representing a negative number.
So 1111 1111 means -127, and 0111 1111 means 127, the range should be between [-127,127]

(3). We all know that the range of numbers that a Byte can express is [-128,127], so how does this -128 come from?

This involves the original code, the inverse code, and the complement of the relevant knowledge, here is a little expansion, I want to understand more clearly, you can learn more.

Background: The original code, the inverse code, and the complement code are generated to solve the problem of the computer doing subtraction and introducing sign bits (positive and negative signs).

Related link: https://blog.csdn.net/zhiwen_a/article/details/81192087

+++++++Byte and bit end+++++++

After knowing the relationship between bytes and placeholders, continue to talk about the problem of type conversion value overflow:

Because the number of storage bits is different, the range of values ​​stored in different basic types is different

When type conversion, the size of the byte space used by the type is different , so up conversion: implicit conversion can be performed directly, down conversion, data overflow may occur . The conversion logic is as follows:

å¨è¿éæå ¥ å¾çæè¿ °

For details of the conversion logic, see this: https://blog.csdn.net/weixin_44736274/article/details/90769042

For the specific conversion java test demo example, see this: https://blog.csdn.net/jreffchen/article/details/81015884

(2). The problem of passing by value or by reference

(1) Creation of basic types: When declaring and initializing local variables of basic data types, the variable names and literal values ​​are stored in the stack and are the real content.

Specific process: such as int age=50;

First, JVM creates a variable named age and stores it in the local variable table. Then it goes to the stack to find out if there is a content with a literal value of 50. If there is, it directly points age to this address. If not, the JVM will be on the stack. Open up a space to store the content of "50" in, and point age to this address. Therefore, we can know that when
we declare and initialize local variables of basic data types, the variable names and literal values ​​are stored in the stack and are the real content.

640?wx_fmt=png

(2) The creation of reference types: reference data types of objects/arrays, variable names are stored in the stack, and variable values ​​store the address of the object, not the actual content of the object.

Specific process: such as Person p=new Person();

When executing Person per;, the JVM first opens up a piece of memory to store the per variable in the variable table in the virtual machine stack. When executing per=new Person(), the JVM creates an instance object of the Person class and opens up a piece in the heap The memory stores this instance, and at the same time assigns the address value of the instance to the per variable. Therefore, it can be seen that
for objects/arrays of reference data types, the variable name is stored in the stack, and the variable value stores the address of the object, not the actual content of the object.

640?wx_fmt=png

Detailed related links: https://mp.csdn.net/postedit/100006266

(3) Understanding of value passing and reference passing

Both passes can be understood as an external variable when calling a method, the method of internal operations will not change the value of this variable .

Use code to demo all situations:

Take int as an example for the basic type:

1.int basic types, in the method reassigned within the parameters and increment method, it will not affect the value of the external parameters .

public class IntPassByValue {
    public static void main(String[] args) {
        int a = 6;
        System.out.println("输出开始的值:" + a);
        changeIntValue(a);
        System.out.println("输出结束1的值:" + a);
        addIntValue(a);
        System.out.println("输出结束2的值:" + a);
    }

    /**
     *重新赋值
     */
    static void changeIntValue(int a) {
        a = 18;
        System.out.println("输出重新赋值方法中间的值:" + a);
    }

    /**
     *内容自增
     */
    static void addIntValue(int a) {
        a += 1;
        System.out.println("输出自增方法中间的值:" + a);
    }
}

As a result, operations within the called method will not affect external parameters :

输出开始的值:6
输出重新赋值方法中间的值:18
输出结束1的值:6
输出自增方法中间的值:7
输出结束2的值:6

2. Class reference type

public class ClassPassByReference {
    public static void main(String[] args) {
        Student student = new Student(1, "张三");
        System.out.println("输出开始的值:" + student.toString());
        changeClassWholeValue(student);
        System.out.println("输出结束1的值:" + student.toString());
        changeClassLocalValue(student);
        System.out.println("输出结束2的值:" + student.toString());
    }

    /**
     *修改引用指向的地址
     */
    static void changeClassWholeValue(Student student) {
        student = new Student(2,"李四");
        System.out.println("输出重新赋值方法中间的值:" + student.toString());
    }

    /**
     *修改引用指向的地址对应的内容
     */ 
    static void changeClassLocalValue(Student student) {
        /*只修改name,不改id*/
        student.setName("王五");
        System.out.println("输出自增方法中间的值:" + student.toString());
    }
}

result:

输出开始的值:Student{id=1, name='张三'}
输出重新赋值方法中间的值:Student{id=2, name='李四'}
输出结束1的值:Student{id=1, name='张三'}
输出自增方法中间的值:Student{id=1, name='王五'}
输出结束2的值:Student{id=1, name='王五'}

Attach the student class:

public class Student {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

3. Reference type String class

public class StringPassByReference {
    public static void main(String[] args) {
        String a = "最初1";
        System.out.println("输出开始的值:" + a);
        changeStringWholeValue(a);
        System.out.println("分割线+++++++string结束++++++++输出结束1的值:" + a);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("stringBuilder开始");
        System.out.println("输出stringBuilder开始的值:" + stringBuilder);
        changeStringBuilderWholeValue(stringBuilder);
        System.out.println("输出stringBuilder修改1的值:" + stringBuilder);
        changStringBuilderLocalValue(stringBuilder);
        System.out.println("输出stringBuilder修改2的值:" + stringBuilder);
    }

    /**
     * 修改引用指向的地址
     */
    static void changeStringWholeValue(String a) {
        a = "修改1";
        System.out.println("输出重新赋值方法中间的值:" + a);
    }

    /**
     * 修改StringBuilder引用指向的地址
     */
    static void changeStringBuilderWholeValue(StringBuilder a) {
        StringBuilder changeStringBuilder = new StringBuilder();
        changeStringBuilder.append("修改指向引用地址");
        a = changeStringBuilder;
        System.out.println("输出修改StringBuilder引用指向的地址:" + a.toString());
    }

    /**
     * 修改StringBuilder引用指向的地址对应的内容
     */
    static void changStringBuilderLocalValue(StringBuilder a) {
        a.append("增加str");
        System.out.println("输出修改StringBuilder引用指向的地址对应的内容:" + a);
    }
}

Results: 1. Since String is an immutable source string and is modified with final, no matter how you manipulate the string, a new str address is generated, and the operation of calling the method will not affect the external parameters. 2. If StringBuilder changes the reference parameter in the method, it will not affect the external parameter. 3. StringBuilder uses the current reference address in the method. Modifying the content of this address will affect the content of the external parameters.

输出开始的值:最初1
输出重新赋值方法中间的值:修改1
分割线+++++++string结束++++++++输出结束1的值:最初1
输出stringBuilder开始的值:stringBuilder开始
输出修改StringBuilder引用指向的地址:修改指向引用地址
输出stringBuilder修改1的值:stringBuilder开始
输出修改StringBuilder引用指向的地址对应的内容:stringBuilder开始增加str
输出stringBuilder修改2的值:stringBuilder开始增加str

Summary : 1. Formal parameters and actual parameters. The external parameters are actual parameters. When the method is called, the formal parameters are new reference parameters instead of actual parameters. (Learn more for yourself) 2. Types are divided into basic types and reference types. 3. The basic type is to put the content on the variable in the stack. If you need to create a new content, you need to create a new variable. If you call the method, the formal parameter and the actual parameter are two different reference variables, so the content change does not affect each other, so the basic The operation parameters in the method called by the type will not affect the external actual parameters. 4. The reference type class is to create a reference on the stack, and the address points to the content created on the heap. The actual parameter represented by the formal parameter of the class call method is the address of the class. If the address of the formal parameter is changed, the external reality will not be affected. The address and content of the participants. If the content of the pointed address is modified according to the formal parameters, the content of the external actual parameters will be affected. 5. The reference type has a String. Since string is a final type, creating a string cannot be changed (this can be understood in depth), so every time the formal parameter is modified, a new address and content will be generated, and the original point will not be modified The content of the address.

Guess you like

Origin blog.csdn.net/Mint6/article/details/100006266