Будет ли создан новый объект в строке i++ или же инкрементируется тот на который ссылаемся? public static void main(String[] args) { Integer i = 8 inc(i) System.out.println(i) } public static void inc(Integer i) { i++ System.out.println(i) } Точнее не так, я уверен, что старый объект останется не тронутым, но что произойдет в строке i++? Получается, создастся новый объект?
Ответ Инкремент в данном случае эквивалентен присваиванию: i = i+1 , т.е. значение будет распаковано, прибавлена единица, полученное значение будет запаковано обратно в i. По шагам: int value = i //получаем примитив value++ i = value //запаковываем в новый объект Будет ли создан новый объект в строке i++ или же инкрементируется тот на который ссылаемся? Класс Integer — неизменяемый и сам по себе инкрементироваться не может. Поведение инкремента описано в спецификации (15.14.2. Postfix Increment Operator ++) The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value. At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored. Т.е. оператор увеличивает значение, которое запаковывается если того требует тип переменной.