Java constant pool and Java constant pool
For an interview question on the internet, find the output result:
- /**
- *
- * @author DreamSea 2011-11-19
- */
- public class IntegerTest {
- public static void main(String[] args) {
- objPoolTest();
- }
-
- public static void objPoolTest() {
- Integer i1 = 40;
- Integer i2 = 40;
- Integer i3 = 0;
- Integer i4 = new Integer(40);
- Integer i5 = new Integer(40);
- Integer i6 = new Integer(0);
-
- System.out.println("i1=i2\t" + (i1 == i2));
- System.out.println("i1=i2+i3\t" + (i1 == i2 + i3));
- System.out.println("i4=i5\t" + (i4 == i5));
- System.out.println("i4=i5+i6\t" + (i4 == i5 + i6));
-
- System.out.println();
- }
- }
Output result
i1=i2truei1=i2+i3 truei4=i5falsei4=i5+i6true
Some Understandings: first, what is a constant pool? According to Baidu's answer, the constant pool is a special storage space in JVM. It is used for storage classes, interfaces, constants in methods, and some string constants. Of course, it can also expand the constants generated by the executor and put them in the constant pool. It has been determined during the compilation period that it is part of the existing. class file. That is to say, when the program runs without dynamic data input, it already exists, which greatly improves the efficiency of program operation.
The reason for the above questions is as follows: Integer first = If the two sides are objects, the reference of the two objects is the address rather than the value. I4 and i5 are two different objects, so the output falsei1 is equal to i2 because there is a block of code in Integer for constant pool, which is stored in-128 ~ The constant value between 127, so each number in the range will not open up another address, that is, i1 and i2 are the same object, so the output is true. Why does the second i1 = i2 + i3 return true? This is because java has the binning feature. i1, i2, and i3 are all objects, however, in the operation, it is automatically converted to the int type before comparison. At this time, = is used to compare the operation values, so equal, and the fourth is the same.
Think about the result if Integer i1 = 128; Integer i2 = 128; System. out. println (i1 = i2? Yes, the program outputs false because 128 is not in the constant pool of Integer.
Let's talk about the String constant pool String s1 = "hello"; String s2 = "hello" String s3 = new String ("hello"); System. out. println (s1 = s2); System. out. println (s1 = s3); what is the result? Answer: truefalse: the String created with new String () is an object that is not a constant and cannot be determined during the compilation period. Therefore, the String created with new String () is not placed in the constant pool, they have their own address space. OK.
String s4 = "he" + new String ("llo"); System. out. println (s1 = s4 );
Result? The answer is false, so as long as it is a new object in the String, it is a new object. If the two objects are not equal, the result must be false.