Difference between a string and an array of characters

前端 未结 7 2059
一整个雨季
一整个雨季 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:52

    The first one compiles. The second one doesn't.

    A char[] is just that: an array of primitive numbers of type char. All it provides is a length attribute, and a way to get and set a char at a given index.

    A String is an object, of type java.lang.String, which has a whole lot of useful methods for manipulating Strings. Internally, it uses a char array.

    Another important feature of String is that it's immutable. You can pass a String to any method and be sure that this method won't change the contents of the String. That is not the case with a char array.

    Regarding memory, a String consumes some more bytes, but that's generally not what should guide your design decisions: generally, using a char array is not what you should do.

提交回复
热议问题