Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are String Arrays mutable?

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

like image 589
mrjasmin Avatar asked Apr 20 '13 21:04

mrjasmin


People also ask

Are string arrays mutable in C?

Strings are immutable. Character Arrays are mutable.

Is array mutable or immutable?

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.

Is string mutable or immutable?

String is an example of an immutable type. A String object always represents the same string.

How do you make a string array mutable in Java?

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.


1 Answers

The Strings 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?

like image 187
Luiggi Mendoza Avatar answered Sep 20 '22 06:09

Luiggi Mendoza