The object of any of the wrapper classes is a full-fledged instance in dynamic memory, in which its immutable value is stored. What is meant by an immutable value?
1 answer
The immutable value is the value of the primitive for which the object is a wrapper. For example, for int - the java.lang.Integer shell for long - the shell is java.lang.Long .
To make sure - open the source code of the java.lang.Integer class:
/** * The value of the {@code Integer}. * * @serial */ private final int value; /** * Constructs a newly allocated {@code Integer} object that * represents the specified {@code int} value. * * @param value the value to be represented by the * {@code Integer} object. */ public Integer(int value) { this.value = value; } This private final int value is the immutable value.
UPD: That is, declaring Integer somevar = 1; in fact, something like this is done: Integer somevar = new Integer(1); Further, if we want to change the value of somevar = 2 , then the variable somevar will already point to another object, rather than overload the previous one. and the previous object will be assembled by the garbage collector if it is no longer referenced
- Why does this code work? In theory, we cannot change the value in this way. Integer var = new Integer (0); var = 1; - jisecayeyo
- @jisecayeyo - updated the answer. - cache
|