java – Which is the priority: auto-packing or auto-packing?


public class Test {
    public static void main(String[] args) {
        Integer t = 1;
        int s = 1;
        System.out.println(s != t);  // (*)

Question: what does the compiler do with the string (*) ? I don't understand whether it is unpacking t , or packing s
A wise man, he writes that "autoboxing" is going on here, but I can't contact him and I don't know why he writes like that.
I can only assume that since we have found Object some_obj in comparison, which is Integer t , then there is a comparison by references, and int s autopacked.
From the results of the program: t==s – true. I do not know why this is so … It seems because there is some method that for Integer , String and the like leads an object to some form, replacing a reference to an object of the same nature, so that == works. For example, two "different" strings, for example: "Hello" and "Hello" after calling this method in the == comparison give true .

Total: I really want to see some documentary explanation of what is happening, what leads to what, and why the result of the line (*) is false , which in principle means: t and s are equal. But in what sense are they equal? Links, numbers? … The bytecode did not help me, there is no way to understand how this comparison works.


t (that is, a conversion from Integer to int ), followed by the usual comparison of primitives (that is, values ​​of type int ).

To understand why this happens, let's turn to the Java specification .

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

If the operands of a comparison operator are both of a numeric type, or one of the operands is a numeric type and the other can be converted to a numeric type, then the operands are subject to a binary numeric promotion .

In the case of comparing int and Integer operand type int is a primitive type and operand type Integer can be converted to a numeric type. In principle, it does not matter how the binary numeric promotion is translated, it is only important that the actions described in the corresponding section of JLS 5.6.2 are performed:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

If one of the operands is a reference type, then unboxing occurs.

In our case, an Integer unpacked and an int obtained. Then two primitives ( int values) are compared in the usual way.

Scroll to Top