How are these declarations different from each other?
String s=\"MY PROFESSION\";
char c[]=\"MY PROFESSION\";
What about the memory allocation
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 s="MY PROFESSION";
s
is immutable i.e content of String
is intact can not be modified. 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 spacec2
is built on the fly in the stack frame by loading individual character constantsc1
& c2
are mutable i.e content of Array
can be modified. c2[0]='B'
StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");
sb
and sbu
are mutable. sb.replace(0, 1, 'B');
sb
and sbu
are stored in heapsb.append( '!');
StringBuffer
's methods are synchronised while StringBuilder
's methods are not