Lets look at some code.
public class Ints {
public static void main(String[] args) {
Integer iW;
for (iW = 1; iW < 4; iW++)
System.out.println(iW);
int i = iW;
iW += 6;
System.out.println(String.format("iW = %d, i = %d", iW , i));
}
}
This should be rather familiar. But now, lets look at what it compiles and decompiles to:
public class Ints {
public Ints() {
}
public static void main(String[] args) {
Integer iW;
for(iW = Integer.valueOf(1); iW.intValue() < 4; iW = Integer.valueOf(iW.intValue() + 1)) {
System.out.println(iW);
}
int i = iW.intValue();
iW = Integer.valueOf(iW.intValue() + 6);
System.out.println(String.format("iW = %d, i = %d", new Object[]{iW, Integer.valueOf(i)}));
}
}
And there you see it happening - the conversion of the Integer
to an int
and back again.
The line that you thought was iW += 6
is actually iW = Integer.valueOf(iW.intValue() + 6);
This is a process known as boxing (that's a Java Tutorial from Oracle - rather good read).
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int
to an Integer
, a double
to a Double
, and so on. If the conversion goes the other way, this is called unboxing.
This is done by the compiler for you. It makes the code easier to write. And as long as you aren't doing things you shouldn't (like comparing equality between Integers with ==
which can bite you in the posterior quite hard), its doing what you want it to.
If you fire up a debugger you will see these objects being created or recalled form other sources.
On my machine, when iW
is 1, the actual object is Integer@426
under the scenes. When iW
is 2, the actual object is Integer@432
and so on. I haven't changed Integer@426 (value=1) when it is incremented - rather a new object is created that has a value one higher.
What immutable actually means is that you cannot do iW.setValue(10)
. That doesn't work. You cannot change the state of the object that iW points to. With autoboxing, you can quickly and easily change which object you are pointing to, but the underlying object cannot be changed.
String is immutable - even though the abomination feature of String foo = "foo"; foo += "bar";
works (thats actually more involved than the Integer magic as it means allocating a new StringBuilder). Look also at BigInteger, Color or InetAddress. Look for the methods that will allow you to mutate the state of the object that you have. That is what immutable means.
String foo = "foo"; foo = "bar";
- String is immutable.foo
is a variable. – user40980 Feb 16 at 22:58