0

I have very simple code

    
    public static void main(String[] args) {
        Integer num = new Integer(1);
        Integer num1 = num;
        num++;
        System.out.println(num);
        System.out.println(num1);
    }
}

I expected both num and num1 value as 2 as num points to the same object as num1, but surprisingly the value of num is 2 and num1 is 1. The increment operator is creating a new object instance and assigning it to num reference.

Any reasons for it?

Kumar
  • 1,536
  • 2
  • 23
  • 33
  • 1
    See https://stackoverflow.com/questions/5560176/is-integer-immutable – Scary Wombat Feb 15 '22 at 06:22
  • 1
    There's a lot happening there. But the confusion is probably due to the fact that `Integer` is an `Object` type, which makes you expect references to be reused. Besides the fact that `Integer` is not mutable, you also have complications introduced by autoboxing. But your question should be answered if you just remember that an Integer object can't be mutated, so any operation (unary or binary) will create a new Integer object. – ernest_k Feb 15 '22 at 06:25
  • 1
    While I'm sure "Is Integer Immutable" contains all information future visitors need to get that answer to this question, it is unclear what OP needs - "The increment operator is creating a new object instance and assigning it to num reference." - indeed it is the answer already written in the question... So Kumar, could you please clarify what exactly you need help with? Some spec links, historical reasoning, something else? – Alexei Levenkov Feb 15 '22 at 06:28

0 Answers0