A final object's value could be changed, right? i.e. not the reference itself could be re-assigned, but the contents of the object the reference is pointing to could be changed.
But how does this work out in the case of wrapper objects. For example given,
When you can change the contents of an object, the object is mutable. The ArrayList class is mutable because you can add and remove elements from it. Wrapper objects, however, are immutable, meaning you cannot alter the contents of the object. The String class is also immutable. Methods like substring() and replace() return a new String instance, leaving the original one untouched. So because wrapper objects are immutable, there's no way to change the value of an Integer object. And, in your case, since the variable is final, you can't even reassign the reference.
Thanks for the detailed explanation. That helps. I just have one more questoin. In that case i.e. wrapper objects being immutable and particular final wrapper objects being very much so, why aren't they being allowed inside switch statements as case values?
final Integer x = 5;
case x: //isn't allowed
even though logically x is a constant and it is immutable
final int x = 5;
case x: //is allowed
When I compile (1), the compiler gives the following error:
"constant expression required", even though as you very well explained "final Integer x = 5"; is immutable, which means it is a constant. But still the compiler insists that it requires a constant expression. What gives? Please, I don't want to hear that the JLS is the reason.
Larry Olson wrote:Please, I don't want to hear that the JLS is the reason.
Then ignore this answer.... When the compiler is complaining about it not being a constant. It is referring to a compile time constant.
And the definition of compile time constant is very specific. Wrapper objects are not candidates of being compile time constants. The operations needed to box and unbox the values are not allowed of compile time constants.