Write the execution results of the following three pieces of code:
Code snippet 1
Integer integer1 = 100; Integer integer2 = 100; System.out.println(integer1 == integer2);
Code snippet 2
Integer integer3 = 1000; Integer integer4 = 1000; System.out.println(integer3 == integer4);
Code snippet 3
Integer integer5 = new Integer(100); Integer integer6 = new Integer(100); System.out.println(integer5 == integer6);
1 true 2 false 3 false
In code snippet 1 , 100 is within the
bytevalue range, and
Integerobject is created and saved in the
byteconstant pool when it is created , and
integer2the value is
integer1equal to and the object in the constant pool is reused directly. Therefore,
integer2is the same object.
In code snippet 2 , 1000 is not in the
bytevalue range, and the object is recreated every time the value is assigned. Therefore,
integer4are two different objects.
In code snippet 3 , because the keyword is used
new, no matter whether the value is within the
newan object is created in the heap memory every time . Therefore,
integer6are two different objects.
Note: Under normal circumstances, what is
int hashCode = object.hashCode();returned is the memory address of the object, but it
hashCode()may be rewritten. Therefore,
int hashCode = System.identityHashCode(object);the memory address of the object can be obtained through methods .
Integer the process of creating an object