Difference between a string and an array of characters

前端 未结 7 2136
一整个雨季
一整个雨季 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条回答
  •  Happy的楠姐
    2021-02-01 10:59

    How this declaration differentiate from each other?

    Your first line produces a String instance. Your second line is simply invalid; perhaps you meant:

    char[] c = {'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N'};
    

    which creates char[] filled with those characters.

    what about its memory allocation?

    Storing a string as a String is slightly different memory-wise than storing it as a char[]. There are similarities though: both are objects, and have the usual object overhead.

    However, a String holds a char[] internally, so naturally a String consumes more memory. Furthermore, String has 3 int fields (offset, count and hash) whereas char[] has the single int field length.

    For example, storing "MY PROFESSION" as a String:

    • 3 int fields: 12 bytes
    • char[] field: 8 bytes
      • int field: 4 bytes
      • object overhead: 8 bytes
      • 13 characters: 26 bytes
    • object overhead: 8 bytes

    This comes out to about 66 bytes. I say "about" because some of this is dependent on the VM. The corresponding char[] of length 10 only consumes 38 bytes, as you can see. The memory difference here is quite negligible so you shouldn't worry about it (and just use a String!). It becomes even more insignificant the longer the string you are trying to store becomes.

提交回复
热议问题