How are these declarations different from each other?
String s=\"MY PROFESSION\";
char c[]=\"MY PROFESSION\";
What about the memory allocation
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
:
int
fields: 12 byteschar[]
field: 8 bytes
int
field: 4 bytesThis 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.