Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Integer Immutable

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?

like image 758
K.Steff Avatar asked Apr 06 '11 00:04

K.Steff


People also ask

Is integer immutable data type?

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.

Is Java Integer class immutable?

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.

Why is integer immutable in python?

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.

Is integer immutable in C#?

Integer variables are mutable. However, integer literals are constants, hence immutable.


1 Answers

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).

like image 129
Travis Webb Avatar answered Sep 22 '22 21:09

Travis Webb