The difference between boxing and unboxing, == and equals in java

1. Concept: Boxing is to automatically convert basic data types to wrapper types; unboxing is to automatically convert wrapper types to basic data types.

For example: Integer i =1; //It will be boxed automatically. When the above code is executed, the system will execute it for us: Integer total = Integer.valueOf(99);

               int j = i; //The box will be automatically unpacked . When the code above is executed, the system executes it for us:  int totalprim = total.intValue();

2、

Integer i1 = 127;
 Integer i2 = 127;
 Integer i3 = 128;
 Integer i4 = 128;
 
 
System.out.println(i1==i2);  //true
System.out.println(i3==i4);  //false

When -127<i<128, the number will be taken from the cache when unboxing, so i1=i2, in other cases, a memory will be reallocated when unboxing, so i3! =i4.

3、

Double i1 = 127.0;
Double i2 = 127.0;
Double i3 = 128.0;
Double i4 = 128.0;
System.out.println(i1==i2); //false
System.out.println(i3==i4); //false

Floating-point numbers are different from integer types, because integer types have a limit on the number of numbers within a certain range, and floating-point numbers have no limit, so floating-point numbers are all re-allocated memory.

4. boolean: boolean creates two objects of true and false in advance, so these two objects are called directly, so all boxed true or false are equal

5. Summary of the same different packing

6、

Integer num1 = 400;  
int num2 = 400;  
System.out.println(num1.equals(num2)); //true

At this time, because int is an instance class of Integer, the value of num1 is compared with nums2 when judging equals internally.

return (o instanceof Integer) && (((Integer) o).value == value);

7. When the operation is performed, the encapsulated class will be automatically unboxed, so == returns true

8. String rewrites the equals method of Object: "==" compares the values ​​of the two variables themselves, that is, the addresses of the two objects in memory. equals compares the contents of two strings for equality

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325685324&siteId=291194637