3 ms·
That's tautological. The question is not why String behaves as a reference type - obviously, because it is a reference type. The question is, why is String a re
by int_19h 9y ago
That's tautological. The question is not why String behaves as a reference type - obviously, because it is a reference type. The question is, why is String a reference type, when it has such obvious value semantics?
And it's a perfectly valid question. The real answer is that they wanted strings to have methods, so it had to be a class, because primitives can't have methods; and Java doesn't have value classes, so it had to be a reference type. So the reason is a deficiency in the language.
A better question is, why .NET string is a reference type (with overloaded == to make it behave like a value, even!). It could have easily been a struct. I suspect that this is one of those decisions that were made very early on to basically be like Java because that's what people expect; and then it became impossible to change without major breakage.
The real problem is that most implementations that do reference / value type distinction, mix up semantics and implementation. What we really need is the ability to say that something 1) doesn't have a meaningful identity, and 2) is immutable (in a sense that you can't replace individual components of that object; you still can replace the whole object). When you combine these two, you get something that can be implemented as a value type under the hood, but the programmer doesn't need to think about it. They can just continue treating it as a reference, just as they do in Python. There's no way to tell the difference.