I wonder if String arrays in Java are mutable ? I know that Strings are immutable, but how about string Arrays ?
If I have a string array, and change the content, will a new string object be created ? Or will the actual value just be changed ?
Thanks in advance
Strings are immutable. Character Arrays are mutable.
In JavaScript, objects and arrays are mutable by default, but primitive values are not — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned.
String is an example of an immutable type. A String object always represents the same string.
In a mutable string, we can change the value of string and JVM doesn't create a new object. In a mutable string, we can change the value of the string in the same object. To create a mutable string in java, Java has two classes StringBuffer and StringBuilder where String class is used to the immutable string.
The String
s contained in the String[]
are indeed immutable, but the array is mutable.
This is well explained in this answer:
- Immutability means that objects of a certain type can not change in any meaningful way to outside observers
Integer
,String
, etc are immutable- Generally all value types should be
- Array objects are mutable
- It may be an array of references to immutable types, but the array itself is mutable
- Meaning you can set those references to anything you want
- Also true for array of primitives
- An immutable array will not be practical
- References to objects can be shared
- If the object is mutable, mutation will be seen through all these references
EDIT:
Somewhat related: Why can't strings be mutable in Java and .NET?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With