How are these declarations different from each other?
String s=\"MY PROFESSION\";
char c[]=\"MY PROFESSION\";
What about the memory allocation
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.