Skip to main content
3 of 3
added 265 characters in body
JacquesB
  • 61k
  • 21
  • 133
  • 187

A string is immutable, correct. It does behave somewhat like a (built in) value type, but this is mostly a consequence of both being immutable.

An array is not immutable, even if the elements it holds are immutable. So if an array slot holds a string, you can change it to a different string. This does not change any of the strings, it just changes the array. So yes, your guess is correct.

A string is fundamentally a reference type, which means the variable x does not actually contain a string, it contains a reference to string. When you set the variable to a different string, this only changes which reference the variable holds, but both strings are unaffected. Same thing with an array of strings - it is not really an array of strings but rather an array of references to strings. When you change an array item, you only change the cell to contain a different reference, but none of the actual strings are affected.

So it is not correct to say the string is destroyed when a variable is assigned a different reference. The string is unaffected. (Due to garbage collection, objects for which no references exists anymore may be removed from memory, but this is unpredictable and implementation specific.)

By the way, none of this is affected by the fact that strings are immutable! What you describe is fundamental for how reference types work, and since you are only changing references and not the string/object itself, it doesn't matter if it is immutable or not.

JacquesB
  • 61k
  • 21
  • 133
  • 187