Difference between a string and an array of characters
java
Solution
To correct compilation error replace with one of the below `char[]` statement
String s = "MY PROFESSION";
char c1[] = "MY PROFESSION".toCharArray();
char c2[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N' };
StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");
Following section compares above statement with each other
String Constant
String s="MY PROFESSION";
- "MY PROFESSION" is a constant and stored in String pool see Where does Java's String constant pool live, the heap or the stack?
- `s` is immutable i.e content of `String` is intact can not be modified.
- Size/Length of string is fixed (not possible to append)
Character Array
char c1[]="MY PROFESSION".toCharArray();
char c2[]={'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N'};
- `c1` holds copy of String's underlying array (via `System.arraycopy`) and stored in heap space
- `c2` is built on the fly in the stack frame by loading individual character constants
- `c1` & `c2` are mutable i.e content of `Array` can be modified. `c2[0]='B'`
- Size/Length of Array is fixed (not possible to append)
StringBuilder / StringBuffer
StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");
- Both `sb` and `sbu` are mutable. `sb.replace(0, 1, 'B');`
- Both `sb` and `sbu` are stored in heap
- Size/Length can be modified. `sb.append( '!');`
- `StringBuffer`'s methods are synchronised while `StringBuilder`'s methods are not
Problem
How are these declarations different from each other? ``` String s="MY PROFESSION"; char c[]="MY PROFESSION"; ``` What about the memory allocation in each case?