Is Integer Immutable

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

Is integer immutable or mutable?

Two things are at play. First, int's are objects that can be bound to more than one variable. Second, python caches a small cluster of small integers that tend to be used a lot for efficiency

x = 5       # get the cached `5` object and bind it to x
y = x # take whatever object is bound to x and also bind it to y
x += 1 # take whatever object is bound to x, call its `__iadd__`
# method and bind the return value to x. `int.__iadd__`
# adds the integers and since it is small, returns the
# cached `6` object.

Notice that assignment does not create a new object. It simply puts a reference to an object into a variable, much like adding a key/value pair to a dictionary.

Why are Integers immutable in Java?

You won't find a mandatory reason why java.lang wrappers must be immutable. Simply because it's a design decision. They could have decided otherwise. The language designers had to choose between mutable and immutable. And they chose immutable. That's it.

There are some compelling (IMO) reasons though to make them immutable:

It's consistent with String. The same reasoning you provided for String to be immutable applies to Integer etc. as well (e.g. think of a port number in a property map). This generally applies to any mutable type.

Immutable types rule out a plethora of hard to find mistakes one can make where one involuntarily changed an objects member value by modifying the value obtained through a getter. It saves a lot of defensive copying when the type is immutable. The most infamous example is java.util.Date, which is generally a pain to use because it's mutable (API issues aside).

Also immutable types allow for the use of shared instances, like e.g. Integer does for commonly used values (see Integer.valueOf(int)).

Why are integers immutable in Python?

Making integers mutable would be very counter-intuitive to the way we are used to working with them.

Consider this code fragment:

a = 1       # assign 1 to a
b = a+2 # assign 3 to b, leave a at 1

After these assignments are executed we expect a to have the value 1 and b to have the value 3. The addition operation is creating a new integer value from the integer stored in a and an instance of the integer 2.
If the addition operation just took the integer at a and just mutated it then both a and b would have the value 3.

So we expect arithmetic operations to create new values for their results - not to mutate their input parameters.

However, there are cases where mutating a data structure is more convenient and more efficient. Let's suppose for the moment that list.append(x) did not modify list but returned a new copy of list with x appended.
Then a function like this:

def foo():
nums = []
for x in range(0,10):
nums.append(x)
return nums

would just return the empty list. (Remember - here nums.append(x) doesn't alter nums - it returns a new list with x appended. But this new list isn't saved anywhere.)

We would have to write the foo routine like this:

def foo():
nums = []
for x in range(0,10):
nums = nums.append(x)
return nums

(This, in fact, is very similar to the situation with Python strings up until about 2.6 or perhaps 2.5.)

Moreover, every time we assign nums = nums.append(x) we would be copying a list that is increasing in size resulting in quadratic behavior.
For those reasons we make lists mutable objects.

A consequence to making lists mutable is that after these statements:

a = [1,2,3]
b = a
a.append(4)

the list b has changed to [1,2,3,4]. This is something that we live with even though it still trips us up now and then.

Java : Integer Immutability

Shouldn't I get True,True.???

no, you get false since those objects are not stored in any integer pool (more or less the same principle as string-pool), and therefore i and j are pointing to a totally different reference.

there is a possible case where you can get such a comparing returning true, and that is for values until 127...

one example to verify that is:

 Integer b2=128;
Integer b3=128;
System.out.println(b2==b3);

that will print false.

but this

Integer b2=127;
Integer b3=127;
System.out.println(b2==b3);

will print true!

Why are C# number types immutable?

Firstly:

What is the purpose of returning a new object each time you want to change the value?

I think you might be mistaken about how value types work. This isn't some costly operation like you may be imagining; it's simply the overwriting of data (as opposed to, e.g., dynamic allocation of new memory).

Secondly: here's a very simple example of why numbers are immutable:

5.Increase(1);
Console.WriteLine(5); // What should happen here?

Granted, that is a contrived example. So let's consider a couple more involved ideas.

Mutable reference type

First, there's this one: what if Integer were a mutable reference type?

class Integer
{
public int Value;
}

Then we could have code like this:

class Something
{
public Integer Integer { get; set; }
}

And:

Integer x = new Integer { Value = 10 };

Something t1 = new Something();
t1.Integer = x;

Something t2 = new Something();
t2.Integer = t1.Integer;

t1.Integer.Value += 1;

Console.WriteLine(t2.Integer.Value); // Would output 11

This seems to defy intuition: that the line t2.Integer = t1.Integer would simply copy a value (actually, it does; but that "value" is in fact a reference) and thus that t2.Integer would remain independent of t1.Integer.

Mutable value type

This could be approached another way, of course, keeping Integer as a value type but maintaining its mutability:

struct Integer
{
public int Value;

// just for kicks
public static implicit operator Integer(int value)
{
return new Integer { Value = value };
}
}

But now let's say we do this:

Integer x = 10;

Something t = new Something();
t.Integer = x;

t.Integer.Value += 1; // This actually won't compile; but if it did,
// it would be modifying a copy of t.Integer, leaving
// the actual value at t.Integer unchanged.

Console.WriteLine(t.Integer.Value); // would still output 10

Basically, immutability of values is something that is highly intuitive. The opposite is highly unintuitive.

I guess that is subjective, though, in all fairness ;)

Are Java primitives immutable?

Will this allocate a new memory location? Or just replace the original value?

Java does not really make any guarantees that variables will correspond to memory locations; for example, your method might be optimized in such a way that i is stored in a register — or might not even be stored at all, if the compiler can see that you never actually use its value, or if it can trace through the code and use the appropriate values directly.

But setting that aside . . . if we take the abstraction here to be that a local variable denotes a memory location on the call stack, then i = 11 will simply modify the value at that memory location. It will not need to use a new memory location, because the variable i was the only thing referring to the old location.

Does this mean that primitives are immutable?

Yes and no: yes, primitives are immutable, but no, that's not because of the above.

When we say that something is mutable, we mean that it can be mutated: changed while still having the same identity. For example, when you grow out your hair, you are mutating yourself: you're still you, but one of your attributes is different.

In the case of primitives, all of their attributes are fully determined by their identity; 1 always means 1, no matter what, and 1 + 1 is always 2. You can't change that.

If a given int variable has the value 1, you can change it to have the value 2 instead, but that's a total change of identity: it no longer has the same value it had before. That's like changing me to point to someone else instead of to me: it doesn't actually change me, it just changes me.

With objects, of course, you can often do both:

StringBuilder sb = new StringBuilder("foo");
sb.append("bar"); // mutate the object identified by sb
sb = new StringBuilder(); // change sb to identify a different object
sb = null; // change sb not to identify any object at all

In common parlance, both of these will be described as "changing sb", because people will use "sb" both to refer the variable (which contains a reference) and to the object that it refers to (when it refers to one). This sort of looseness is fine, as long as you remember the distinction when it matters.



Related Topics



Leave a reply



Submit