1: preface
I believe we have all been asked a question in the interview, this question is in recent years the interviewer difficult people more common a question, so it is also known to everyone, is very simple in nature, but is also a very basic topic.
Integer a = 100;
Integer b = 100;
System.out.println(a == b);
Integer a = 180;
Integer b = 180;
System.out.println(a == b);
Copy the code
The first one is true, the second one is false, and you already know that
2: automatic packing and unpacking
We all know! The core idea of Java is that everything is an object, but actually, for the convenience of writing code in general, eight basic data types are preserved: byte, short, char, int, Long, float, double, and Boolean
So the question is: How does this work
// A is an Integer object type. 100 is a basic int. Integer A = 100;Copy the code
That’s when our smart compiler calls valueOf to do the boxing
Automatic unboxing does the reverse, using the object’s intValue() method to unbox the underlying data type
3: Answer the above == different questions
So let’s revisit the above problem, and I’ll add an extra distraction term
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // -> true
Integer a = 180;
Integer b = 180;
System.out.println(a == b); // -> false
Integer a = new Integer(100);
Integer b = new Integer(100);
System.out.println(a == b); // -> false
Copy the code
So we need to understand the meaning of ==, the base type == is to compare whether the values are equal, object type == is to compare whether the memory address is the same
ValueOf (), we can see that we do a cache check when we load the container. If the value is in the range [-128,127], we take a cache object, so a and B are the same. The second 180 is out of range. It’s going to create a new Integer object, and it’s going to have a different memory address
New Integer(100) actually creates the object itself, without using boxing, but I don’t think anyone would use that
4:
In fact, many small details of Java design, small questions contain the wisdom and efforts of designers, we look at these interview questions, should carefully consider why this design, and then their own work can also use these clever design and knowledge!!