Will this allocate a new memory location? Or just replace the original value?
Java does not really make any guarantees that variables will correspond to memory locations; for example, your method might be optimized in such a way that
i is stored in a register — or might not even be stored at all, if the compiler can see that you never actually use its value, or if it can trace through the code and use the appropriate values directly.
But setting that aside . . . if we take the abstraction here to be that a local variable denotes a memory location on the call stack, then
i = 11 will simply modify the value at that memory location. It will not need to use a new memory location, because the variable
i was the only thing referring to the old location.
Does this mean that primitives are immutable?
Yes and no: yes, primitives are immutable, but no, that’s not because of the above.
When we say that something is mutable, we mean that it can be mutated: changed while still having the same identity. For example, when you grow out your hair, you are mutating yourself: you’re still you, but one of your attributes is different.
In the case of primitives, all of their attributes are fully determined by their identity;
1 always means
1, no matter what, and
1 + 1 is always
2. You can’t change that.
If a given
int variable has the value
1, you can change it to have the value
2 instead, but that’s a total change of identity: it no longer has the same value it had before. That’s like changing
me to point to someone else instead of to me: it doesn’t actually change me, it just changes
With objects, of course, you can often do both:
StringBuilder sb = new StringBuilder("foo"); sb.append("bar"); // mutate the object identified by sb sb = new StringBuilder(); // change sb to identify a different object sb = null; // change sb not to identify any object at all
In common parlance, both of these will be described as “changing
sb“, because people will use “
sb” both to refer the variable (which contains a reference) and to the object that it refers to (when it refers to one). This sort of looseness is fine, as long as you remember the distinction when it matters.