Java is an object-oriented programming language. Everything is an object, but for the sake of programming convenience, it still introduces basic data types. In order to treat these basic data types as objects, Java introduces a corresponding wrapper class for each basic data type. The wrapper class for int is Integer. Since Java 5, automatic boxing/unboxing has been introduced to allow the two to be converted to each other, as follows:

Primitive types: Boolean, char, byte, short, int, long, float, double

Wrapper types: Boolean, Character, Byte, Short, Integer, Long, Float, Double

By the way, there are only eight basic datatypes in Java, and all the primitive types are reference types.

Ingeter is a wrapper for int. The initial value of int is 0 and the initial value of Ingeter is null. In addition, there are differences, look at the code:

public class TestInteger { public static void main(String[] args) { int i = 128; Integer i2 = 128; Integer i3 = new Integer(128); System.out.println(i == i2); Println (I == i3); //Integer automatically unboxes to int, so true system.out.println (I == i3); //true, for the same reason as above Integer i4 = 127; Integer i4 = integer.valueof (127); Integer i5 = 127; System.out.println(i4 == i5); //true Integer i6 = 128; Integer i7 = 128; System.out.println(i6 == i7); //false Integer i8 = new Integer(127); System.out.println(i5 == i8); //false Integer i9 = new Integer(128); Integer i10 = new Integer(123); System.out.println(i9 == i10); //false } }Copy the code

Why is i4 true compared to i5, and i6 false compared to i7? ValueOf () caches values between -128 and 127. If Integer i5 = 127, it caches 127. The next time I write an Integer i6 = 127, I fetch it directly from the cache. So the ratio of i4 to i5 is true, and the ratio of i6 to i7 is false.

False for i5 and i8, and i9 and i10, because the objects are different.

The above situation is summarized as follows:

1. Anyway, Integer and new Integer are not equal. New objects are stored in the heap, while Integer constants that are not new are stored in the constant pool (in the method area). They have different memory addresses, so they are false.

2, both integers are non-new, true if the number is between -128 and 127, false otherwise. Integer i2 = integer.valueof (128); The valueOf() function caches numbers between -128 and 127.

3, both of them are new, both of them are false. Again, the memory address is different.

4, int and Integer(whether new or not) are true, because Integer is automatically unboxed into int.

Reference from: www.cnblogs.com/liuling/arc… Blog.csdn.net/jackfrued/a… Blog.csdn.net/login_sonat…