Difference between a string and an array of characters

前端 未结 7 2043
一整个雨季
一整个雨季 2021-02-01 10:18

How are these declarations different from each other?

String s=\"MY PROFESSION\";
char c[]=\"MY PROFESSION\";

What about the memory allocation

7条回答
  •  [愿得一人]
    2021-02-01 10:49

    An array of characters is mutable, in other words, you can replace a character in an array of characters by overwriting the memory location for that character.

    A String is not mutable, in other words, to "replace" a character in a String, you must build a new String with the desired character in place (copying the non-changing parts from the old String).

    While this seems simple, it has a profound impact on the ability to share between Thread (and objects). One String can safely be shared between Threads without extra checks to see if the String is being changed (which might give a Thread an inconsistency read of the String).

    Other optimizations are also possible, since Strings cannot mutate, you can rewire equality operations to be "equals by value". Which means that a "String factory" can return cached copies of the same String, even when two different String objects are requested, because it will become impossible for the two objects to behave differently.

提交回复
热议问题