The difference between int and Integer

  1. Integer is a wrapper class for int, which is a basic data type in Java
  2. Integer variables must be instantiated before they can be used, whereas int variables do not
  3. An Integer is actually a reference to an object, and when you new an Integer, you’re actually generating a pointer to that object. Int stores data values directly
  4. The default value of Integer is null, and the default value of int is 0

Case 1

1Integer i = new Integer(100);

2Integer j = new Integer(100);

3System.out.print(i == j); //false

Copy the code

Since an Integer variable is actually a reference to an Integer object, two Integer variables generated by new are never equal (because new generates two objects with different memory addresses).

Case 2

1Integer i = new Integer(100);

2int j = 100;

3System.out.print(i == j); //true

Copy the code

If an Integer variable is compared with an int variable, the result will be true as long as the values of the two variables are equal.

Example 3

1Integer i = new Integer(100);

2Integer j = 100;

3System.out.print(i == j); //false

Copy the code

Integer variables that are not generated by new are compared to variables generated by new Integer() and the result is false. Because:

  • When the value is between -128 and 127, non-new Integer variables refer to objects in the Java constant pool, while new Integer() variables refer to objects newly created in the heap, and they have different addresses in memory.
  • When the value of a variable is between -128 and 127, the Java API will eventually treat the variable as new Integer(I) (see item 4 below), and the address of the two intergers will also be different.)

Example 4

1Integer i = 100;

2Integer j = 100;

3System.out.print(i == j); //true

Copy the code

1Integer i = 128;

2Integer j = 128;

3System.out.print(i == j); //false

Copy the code

For two non-new generated Integer objects, the comparison result is true if the values of the two variables are in the range -128 to 127, and false if the values are not in the range