The meaning, usage and difference between using Integer and int in java

learning target:

学习目标如下:

  • Clarify the meaning, usage and difference between Integer and int

Learning Content:

1. Differences:
1. Integer is a wrapper class of int, which is a basic data type in Java; 2. Integer
variables must be instantiated before they can be used, while int variables do not need to be instantiated;
3. Integer is actually an object Reference, when new an Integer, a pointer is actually generated pointing to the object, and int directly stores the value
4. The default value of Integer is null, and the default value of int is 0.

2. Comparison of Integer and int
  1. Since Integer is actually a reference to an Integer object, the two Integer variables generated by new are always different, because New generates two different objects with different memory addresses. . The result of the following operation is false
Insert image description here

2. When comparing an Integer variable with an int variable, as long as the values ​​of the two variables are equal, the result will be True (because when the wrapper class Integer is compared with the basic data type, Java will automatically unbox it into int and then compare it. In fact, two int variables are compared), and the result of the following operation is true
Insert image description here

3. When the Integer variable generated by non-new is compared with the Integer variable generated by new Integer, the result is false (because the Integer variable generated by non-new points to the object in the Java constant pool, and the object from new points to the heap. The newly created object has different memory addresses), the following returns false
Insert image description here

4. When comparing two non-new Integer objects, if the value range of the two variables is between -127 and 128, the returned result is true. If the variable values ​​of the two variables are not in this range, , the result of the comparison is false. The following returns true
Insert image description here

The following returns false
Insert image description here


Knowledge summary:

知识小结:

  • 1. The difference between java basic types and reference types:
      basic data types save original values, and reference data types save reference values ​​(reference values ​​refer to the geographical location in the object)
  • 2. Int is the basic data type in Java, and Integer is the encapsulation class of int.
  • 3. Int type data is stored directly in the stack in memory, while Integer type data is stored in objects in the heap.

Guess you like

Origin blog.csdn.net/YHLSunshine/article/details/131730214