What does immutable mean?
Asked Answered
B

10

111

If a string is immutable, does that mean that.... (let's assume JavaScript)

var str = 'foo';

alert(str.substr(1)); // oo

alert(str); // foo

Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?

If the string was mutable, does that mean the 2nd alert() would return oo as well?

Broadbill answered 8/7, 2010 at 1:54 Comment(0)
D
107

It means that once you instantiate the object, you can't change its properties. In your first alert you aren't changing foo. You're creating a new string. This is why in your second alert it will show "foo" instead of oo.

Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?

Yes. Nothing can change the string once it is created. Now this doesn't mean that you can't assign a new string object to the str variable. You just can't change the current object that str references.

If the string was mutable, does that mean the 2nd alert() would return oo as well?

Technically, no, because the substring method returns a new string. Making an object mutable, wouldn't change the method. Making it mutable means that technically, you could make it so that substring would change the original string instead of creating a new one.

Deem answered 8/7, 2010 at 1:57 Comment(2)
The same string if modified and assigned, will update the string var str = 'foo'; str = str.substr(1)); // oo alert(str); // ooAbnormality
What about below code. The string value is changed now. var name = "Santosh"; console.log(name.substr(0,2)); var name = "kumar" console.log(name); How its still immutableDefine
P
103

On a lower level, immutability means that the memory the string is stored in will not be modified. Once you create a string "foo", some memory is allocated to store the value "foo". This memory will not be altered. If you modify the string with, say, substr(1), a new string is created and a different part of memory is allocated which will store "oo". Now you have two strings in memory, "foo" and "oo". Even if you're not going to use "foo" anymore, it'll stick around until it's garbage collected.

One reason why string operations are comparatively expensive.

Plantar answered 8/7, 2010 at 2:16 Comment(5)
Numbers are immutable too.Bountiful
hello from 2015!! "On a lower level, immutability means that the memory the string is stored in will not be modified. " --- this is too restrictive and does not sound right. Immutability is only about userland, the virtual memory may be changed as memory allocator likes as soon as language specification invariants are kept.Velamen
This answer is more logical than the accepeted answer.Ardith
But i can do like var str = 'foo'; i can modify via str = 'bar'. str value got modified this way right?Nacred
@Nacred Nope. You've assigned a new string to the variable pointing to a new location in memory.Plantar
S
14

Immutable means that which cannot be changed or modified.

So when you assign a value to a string, this value is created from scratch as opposed to being replaced. So everytime a new value is assigned to the same string, a copy is created. So in reality, you are never changing the original value.

Subsidy answered 8/7, 2010 at 1:58 Comment(0)
I
10

I'm not certain about JavaScript, but in Java, strings take an additional step to immutability, with the "String Constant Pool". Strings can be constructed with string literals ("foo") or with a String class constructor. Strings constructed with string literals are a part of the String Constant Pool, and the same string literal will always be the same memory address from the pool.

Example:

    String lit1 = "foo";
    String lit2 = "foo";
    String cons = new String("foo");

    System.out.println(lit1 == lit2);      // true
    System.out.println(lit1 == cons);      // false

    System.out.println(lit1.equals(cons)); // true

In the above, both lit1 and lit2 are constructed using the same string literal, so they're pointing at the same memory address; lit1 == lit2 results in true, because they are exactly the same object.

However, cons is constructed using the class constructor. Although the parameter is the same string constant, the constructor allocates new memory for cons, meaning cons is not the same object as lit1 and lit2, despite containing the same data.

Of course, since the three strings all contain the same character data, using the equals method will return true.

(Both types of string construction are immutable, of course)

Imprint answered 8/7, 2010 at 3:40 Comment(0)
C
4

The text-book definition of mutability is liable or subject to change or alteration. In programming, we use the word to mean objects whose state is allowed to change over time. An immutable value is the exact opposite – after it has been created, it can never change.

If this seems strange, allow me to remind you that many of the values we use all the time are in fact immutable.

var statement = "I am an immutable value";
var otherStr = statement.slice(8, 17);

I think no one will be surprised to learn that the second line in no way changes the string in statement. In fact, no string methods change the string they operate on, they all return new strings. The reason is that strings are immutable – they cannot change, we can only ever make new strings.

Strings are not the only immutable values built into JavaScript. Numbers are immutable too. Can you even imagine an environment where evaluating the expression 2 + 3 changes the meaning of the number 2? It sounds absurd, yet we do this with our objects and arrays all the time.

Caylacaylor answered 16/2, 2017 at 4:58 Comment(0)
S
3

Immutable means the value can not be changed. Once created a string object can not be modified as its immutable. If you request a substring of a string a new String with the requested part is created.

Using StringBuffer while manipulating Strings instead makes the operation more efficient as StringBuffer stores the string in a character array with variables to hold the capacity of the character array and the length of the array(String in a char array form)

Sleazy answered 28/5, 2012 at 6:6 Comment(0)
H
2

From strings to stacks... a simple to understand example taken from Eric Lippert's blog:

Path Finding Using A* in C# 3.0, Part Two...

A mutable stack like System.Collections.Generic.Stack is clearly not suitable. We want to be able to take an existing path and create new paths from it for all of the neighbours of its last element, but pushing a new node onto the standard stack modifies the stack. We’d have to make copies of the stack before pushing it, which is silly because then we’d be duplicating all of its contents unnecessarily.

Immutable stacks do not have this problem. Pushing onto an immutable stack merely creates a brand-new stack which links to the old one as its tail. Since the stack is immutable, there is no danger of some other code coming along and messing with the tail contents. You can keep on using the old stack to your heart’s content.

To go deep on understaning immutability, read Eric's posts starting with this one:

Immutability in C# Part One: Kinds of Immutability

Hamrah answered 8/7, 2010 at 2:4 Comment(1)
That quote contains an odd claim - that stack data structure (actually multiple stacks with tail-sharing) is, as a whole, a mutable structure - every push or pop changes the structure. Only the individual items are immutable. And in principle, you could have the same structure but with mutable elements. This happens in some variations of undoable union-find IIRC. Immutability has big advantages, but sharing part or all of a data structure as an optimisation is perfectly possible with mutables. Even if you want apparent immutability for other references, you can always copy-on-write as needed.Romanesque
V
0

One way to get a grasp of this concept is to look at how javascript treats all objects, which is by reference. Meaning that all objects are mutable after being instantiated, this means that you can add an object with new methods and properties. This matters because if you want an object to be immutable the object can not change after being instantiated.

Valenta answered 18/8, 2015 at 23:3 Comment(0)
H
0

Try This :

let string = "name";

string[0] = "N";

console.log(string); // name not Name

string = "Name";

console.log(string); // Name

So what that means is that string is immutable but not constant, in simple words re-assignment can take place but can not mutate some part.

Hyatt answered 14/9, 2020 at 9:21 Comment(0)
G
0

The text-book definition of mutability is liable or subject to change or alteration. In programming, we use the word to mean objects whose state is allowed to change over time. An immutable value is the exact opposite – after it has been created, it can never change.

If this seems strange, allow me to remind you that many of the values we use all the time are in fact immutable. var statement = "I am an immutable value"; var otherStr = statement.slice(8, 17);

I think no one will be surprised to learn that the second line in no way changes the string in statement. In fact, no string methods change the string they operate on, they all return new strings. The reason is that strings are immutable – they cannot change, we can only ever make new strings.

Strings are not the only immutable values built into JavaScript. Numbers are immutable too. Can you even imagine an environment where evaluating the expression 2 + 3 changes the meaning of the number 2? It sounds absurd, yet we do this with our objects and arrays all the time.

Ganny answered 8/5, 2022 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.