Difference between a string and an array of characters

前端 未结 7 2040
一整个雨季
一整个雨季 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条回答
  • 2021-02-01 10:49

    An array of characters is mutable, in other words, you can replace a character in an array of characters by overwriting the memory location for that character.

    A String is not mutable, in other words, to "replace" a character in a String, you must build a new String with the desired character in place (copying the non-changing parts from the old String).

    While this seems simple, it has a profound impact on the ability to share between Thread (and objects). One String can safely be shared between Threads without extra checks to see if the String is being changed (which might give a Thread an inconsistency read of the String).

    Other optimizations are also possible, since Strings cannot mutate, you can rewire equality operations to be "equals by value". Which means that a "String factory" can return cached copies of the same String, even when two different String objects are requested, because it will become impossible for the two objects to behave differently.

    0 讨论(0)
  • 2021-02-01 10:52

    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.

    0 讨论(0)
  • 2021-02-01 10:57

    char is a primitive type. String is a class in which actual data is stored internally as a character array

    char c[]="MY PROFESSION";
    

    will give compilation error.

    Character array is the contiguous storage in memory where characters are stored sequentially.

    Check out this Thread for more details.

    0 讨论(0)
  • 2021-02-01 10:59

    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
    0 讨论(0)
  • 2021-02-01 10:59

    If you see the docs,

         String str = "abc";
    
    is equivalent to:
    
         char data[] = {'a', 'b', 'c'};  //  not 'abc'
         String str = new String(data);
    

    More over String literals are very special in java

    String is backed by a character array internally.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题