I always wonder when it comes to mutability. Why .net designers have developed only stringbuilder class to achieve mutability of string class & not intbuilder for int considering int & string are implemented exactly the same way irrespective of their data types.
-
This makes for good reading: http://channel9.msdn.com/forums/TechOff/58729-Why-are-string-types-immutable-in-C/ – jbutler483 Sep 01 '14 at 12:08
-
Why do you want to make an int mutable? Value types are immutable by definition(1 is always 1). – Tim Schmelter Sep 01 '14 at 12:14
-
@TimSchmelter I dont want to achieve anything by making int mutable its just curiosity – Ulhas Tuscano Sep 01 '14 at 12:19
-
Unlike a mutable `int`, a mutable `BigInteger` would be useful. This shows that, which shows that the need for builders is the cost of constructing a new instance, which mainly depends on the size. – CodesInChaos Sep 01 '14 at 13:01
6 Answers
Many other languages provide similar design for strings: Java with StringBuffer and StringBuilder, Scala with StringBuilder, Python with MutableString though there are other, beter solutions in Python. In C++ strings are mutable, so no need for a builder.
The reason why builder exist for strings is:
- Many languages define string as immutable (any change requires a new object in memory)
- Strings tend to be large, much larger than ints
- [1] and [2] combined cause inefficiency
The reason why builder doesn't exist for int:
- It is simple data structure by itself
- Most CPU have optimised instructions to deal with simple numbers (add, take away, etc)
- Most CPU would efficiently process [2] instructions in just one or a few cycles, using registers or fast CPU cache
- [2] and [3] combined remove the need for optimisation
- There is little need to mutate an int per se, however, if you need to, you can use BitConverter or binary shift operations

- 35,458
- 16
- 93
- 163
To help you understand why there is no IntBuilder
(LongBuilder
, DecimalBuilder
, etc.) consider what operations you would put on these classes if you were to design them. There is very little to be "built" about a number: unlike a string, to which you can append, insert, and delete, numbers can be only replaced with new numbers.
Note that even in cases when the new value is based on an old value (say, in an Add
or a Multiply
method of a hypothetical IntBuilder
) it is essentially a replacement operation, because IntBuilder
can hold a single value. Therefore, your IntBuilder
would end up looking like this:
class IntBuilder {
public int Value { get; set; }
}
That's all you need to have a mutable Int32
. Perhaps a nice set of ToString
, Equals
, and GetHashCode
overrides would be useful, too; maybe, some conversion operators to let you treat IntBuilder
as int
in some contexts would come handy as well. But the essence of the class is captured in the implementation above: all other "building" operations can be modeled with assignments of Value
on your IntBuilder
. But that's hardly a useful class, because of two reasons:
- You can use primitive
int
for mutating an integer within the scope of a single method, and - You can pass primitive
int
by reference if you must achieve mutation in other methods.

- 714,442
- 84
- 1,110
- 1,523
(This question must be a duplicate but I can’t find of what.)
You are asking the wrong question, we all expect most value types to be immutable and expect all primitive types to be value types. However string is a primitive type that is a reference type.
See "In C#, why is String a reference type that behaves like a value type?", "Is string a value type or a reference type?" and "Why is string a reference type?" for the problems the C# deign team was trying to solve.
(Most programming languages find it hard to fit strings into the type system.)

- 1
- 1

- 51,220
- 55
- 213
- 317
I think what you are not considering is how memory in a modern computer works.
When you ask the OS to give you some memory to store data (like a string) that space can be anywhere in the memory address space...
So, let's assume you asked the OS to store a 10 character string (10 * 2 bytes = 20 bytes), so you have your 20 bytes and you place your String data in there.
Now the programmer thinks, let's place another character at the end of that 10 character string... So you ask the OS for another 2 bytes (a single character) but find that those two extra bytes are located at some generic and random location in memory.... Problem; you can't just have 10 characters at one place and the extra 1 at another... So to solve this each time you increase the size of a string the string is destroyed then the total length is requested from the memory pool.
Basic also does this it is just transparent. Your strings are destroyed, you just don't have memory pointers in basic so don't notice.
Here is an analogy to help (best I could think of).
You and some friends go to the TicketMaster web-site to try and buy 5 tickets to the latest concert; you are given seat numbered 523, 524, 525, 526 and 527. Then another one of your friends suggests they want to come too... So you go to the TicketMaster website again in the hopes that you can buy seat 528 or 522 so you can all sit next to one another ... But the site won't let you pick where you want to sit.
Which leaves you two chooses. Either cancel all of your friend's seats and re-book all six or seat that last person somewhere else... But if you sat them somewhere else you might have trouble finding them after... So you decide to pick the first option and to cancel and re-book the full number.
From Link i've posted under OP's question.
EDIT:
http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/ Explains exactly why strings are immutable. This includes:
- Requirement in string pool:
String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
- Caching Hashcode:
The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
- Facilitating the Use of Other Objects:
To make this concrete, consider the following program:
HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));
for(String a: set)
a.value = "a";
In this example, if String is mutable, it's value can be changed which would violate the design of set (set contains unduplicated elements). This example is designed for simplicity sake, in the real String class there is no value field.
- Security:
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
- Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminate the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.
I would also just like to clarify, this answer can be referred to multiple programming languages.

- 24,074
- 9
- 92
- 145
Every time you generate a string a new instance in heap is created, with int usually operation are done on the stack
// increment int in loop
int c = 10;
for (int i = 0; i < 100; ++i)
{
c += 5;
}
Console.WriteLine("c: {0}", c);
c
is a variable on stack, and increment will replace value without using additional memory.
Instead:
// concat string in loop
string acc = "";
for (int i = 0; i < 100; ++i)
{
acc += "A";
}
Console.WriteLine("acc: {0}", acc);
this will create 1 ( string acc = "";
) + 100 ( acc += "A";
) = 101 new object on heap, each
with more memory used ( "A"
, "AA"
, "AAA"
, etc ) putting more pressure on GC, because all these instance except last one are collected. When string are long, this become a performance problem.
With:
// concat string with StringBuilder
var sb = new StringBuilder();
for (int i = 0; i < 100; ++i)
{
sb.Append("A");
}
Console.WriteLine("sb: {0}", sb.ToString());
only two object are created ( the StringBuilder and the sb.ToString()
) and internally an unmanaged memory is used for append, without the need to create new intermediate string. Only with sb.ToString()
the internal unmanged string is copied to an immutable string on heap.

- 909
- 4
- 9
StringBuilder
was added for performance reasons, specific for strings. intbuider
has no sense because int is a simple type: a mutable int would have no sense. as it is explained in another answer:

- 1
- 1

- 1,650
- 15
- 31
-
2_"intbuider has no sense because int is immutable already"_ Strings are also immutable. OP is asking why there is no intbuilder to make it also mutable, so your answer misses the topic.. – Tim Schmelter Sep 01 '14 at 12:11
-
@Tim, `String` is immutable, but `StringBuilder` is not, that is why it was added, is not it? So what is wrong? – Andrej Adamenko Sep 01 '14 at 12:14
-
1Yes, OP asked why there is no `IntBuilder` since `int` is immutable. `String` is also immutable and there is a `StringBuilder`. Your explanation states that there is none because `int` is already immutable. We're going round in circles. – Tim Schmelter Sep 01 '14 at 12:16
-
@Tim, I basically meant this from the beginning. `XXXBuilder` only makes sense for types which allow to be partly changed. `int` is simple. – Andrej Adamenko Sep 01 '14 at 12:21
-
i have removed the downvote. But you should consider to delete the answer anyway because it doesn't add much and even just refers to another answer. – Tim Schmelter Sep 01 '14 at 13:04