What if you want to check if the values of Integer are equal? Of course, instead of using "==", you use the "equals" method to compare. Because, in Java, "==" is to check if the instances pointed to by the reference are the same, and to check if the instance values are equal using the "equals" method. That's why.
So what if you dare to use "==" to compare the values of an Integer instance? See the code below.
Sample.java
public class Sample1 {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println("100=100: " + (i1 == i2));
System.out.println("1000=1000: " + (i3 == i4));
}
}
In this program, "100" and "1000" are compared using "==", but the results are displayed as follows.
100=100: true
1000=1000: false
The results differed depending on the numbers compared. Why does this make a difference?
** As you can see in the comments, this is because the Integer Instance is cached in IntegerCache. Since it has nothing to do with the constant pool, we will correct it. ** **
~~ In order to explain this, it is first necessary to explain "constant pool" which is one of the areas of Java. ~~
Instances of ~~ Integer cannot change their internal state. It is immutable. Therefore, you can reuse the instance, and it is useless to create an instance each time. Therefore, the Java VM creates these instances in advance, stores them in a certain area of memory, and uses them when needed. This area is called the "constant pool". ~~
~~ Similarly, there are other things besides Integer that are subject to this constant pool. For example, a string written in solid source code is also a target for being instantiated in this constant pool. ~~
~~ As mentioned above, the Integer instance is prepared in the constant pool in advance, and the program uses that instance. So why does the above code make a difference between "100" and "1000"? That's because not all Integer instances are on a constant pool. By default, Integer instances in the range -128 to 127 are targeted, and instances outside that range are not provided in the constant pool. ~~
~~ In other words, in the above code, the instance obtained from the constant pool is used for "100", so the instance pointed to by each reference was the same. However, for "1000", since the instance was not prepared in the constant pool, an instance was created each time, and the instance pointed to by each reference was different, and as a result, the result of comparison with "==" became false. It means that it was. ~~
I tried to talk about it in the training for newcomers as a small Java story, and I was happy with it, so I wrote it.
Recommended Posts