I know this is probably very stupid, but a lot of places claim that the Integer class in Java is immutable, yet the following code:
Integer a=3; Integer b=3; a+=b; System.out.println(a);
Executes without any trouble giving the (expected) result 6. So effectively the value of a has changed. Doesn't that mean Integer is mutable? Secondary question and a little offtopic: "Immutable classes do not need copy constructors". Anyone care to explain why?
Most python objects (booleans, integers, floats, strings, and tuples) are immutable. This means that after you create the object and assign some value to it, you can't modify that value. Definition An immutable object is an object whose value cannot change.
It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
Security (3), Easy to use (4) and capacity of using numbers as keys in dictionaries (5) are reasons for taken the decision of making numbers immutable. Has fixed memory requirements since creation time (1). All in Python is an object, the numbers (like strings) are "elemental" objects.
Integer variables are mutable. However, integer literals are constants, hence immutable.
Immutable does not mean that a
can never equal another value. For example, String
is immutable too, but I can still do this:
String str = "hello"; // str equals "hello" str = str + "world"; // now str equals "helloworld"
str
was not changed, rather str
is now a completely newly instantiated object, just as your Integer
is. So the value of a
did not mutate, but it was replaced with a completely new object, i.e. new Integer(6)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With