Probe into integer caused by an integer interview question

Interview questions:

1. It's mentioned in the title. It's jdk1 5 environment.

OK, let's create a new project, create a new class, and copy the code in. Set java compiler to 1.5 I'll talk about this version later.

2. There are two data types, int and integer.

Int is the basic type.

Integer is the object type. The class declaration of integer is as follows:

3. The title declares three integer variables, I01, i03 and I04 What is the difference between the three declarations?

Look at the source code. The constructor is as follows:

This operation of new integer (59) calls the constructor and assigns the value of 59 to the local variable value of integer.

Look at integer Valueof source code:

Here, the valueof method first judges the value of the incoming parameter. If the if condition is met, it returns the cache value.

Otherwise, new returns an integer. The condition in if here is integercache high=127, IntegerCache. low=-128; As can be seen from the class definition of integercache, an array cache is defined in integercache to store integer objects. The static block completes the initialization of the array and stores integer objects between - 128 and 127:

So, for integer The valueof (I) method returns the cached integer object when I is between - 128-127. Otherwise, a new integer object is returned.

59 is passed here, so the object in the cache is returned.

We decompile the class file generated by the source code and find the following:

It can be found that: integer I01 = 59; After decompiling, it is integer valueOf(59);

When comparing "= =" with I01 of integer type and I02 of int type, the decompiled result is: I01 intValue() == i02

These two operations are automatic packing and automatic unpacking. This feature is in Java 1 Only at the beginning. So the first point mentioned that the JDK version is 1.5

If we set the java compiler to less than 1.5 in eclipse / MyEclipse, it will fail to compile:

Type mismatch: cannot convert from int to Integer

Through the above analysis, it is not difficult to get the answer to this question.

I01 = = I02 is equivalent to I01 Intvalue() = = I02 comparison of two values 59 = = 59 -- > true;

I01 = = i03 since 59 is between - 128 and 127, the assignment operations of I01 and i03 return the same object. All are the same object returned from CHCHE, with the same object address. True;

I03 = = I04 i03 is the value from the cache and I04 is the new object. They are not the same object, so false.

I02 = = I04 is similar to the first one, true.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>