Memory representation of Empty String

Viewed 1330

How is an empty string stored internally in the memory? I was thinking about an empty string memory representation and can't quite comprehend it. Is there some specific ASCII value for it? What is an empty string exactly?

2 Answers

A String object is a Java Object like any other. It is an object that has a length attribute, which ultimately is stored in a Java object as an int. An empty String has length 0, and thus that int == 0. In actual implementations, a String object internally has a reference to a char[] object (an array of chars).

For an empty String, that reference might be null. In theory the String implementation might always have a non null array reference, and use the length of the array of chars as the String length int, in which case you question would be equivalent to asking about the memory representation of an empty array.

See the OpenJDK implementation for example:

 private final char value[];

is the reference to the array of characters

 private final int count;

is the length of the String, as you can see for the default constructor, which creates an empty String:

 public String() {
    this.offset = 0;
    this.count = 0;
    this.value = new char[0];
 }

(You might be wondering why that implementation has an offset. This is so a sub-string can share the same character array as its parent string, which reduces memory use in many cases).

  • An empty string is a string whose length is 0. It is the same as a string whose length is greater than 0, for all of them are allocated with a memory block to store the variable.
  • All the strings are readonly, that is to say, the memory block can not be resized after being initialized. In some code, we can see

    str1 = str1 + str2

    but actually str1 isn't being resized because of the copy-on-write rule. The system re-allocates a new memory block to store the new result and changes the pointer of str1 to the new one.

  • In basic, the string is an array; the empty string is just a character array with no elements, length is 0, but there is no difference between an empty string or a non-empty string. Both of them have a memory address, the pointer.

  • If you know the string indicator in C/C++, it is just a char * pointer, it always ends with a '\0' character. When you read a string, there will be a loop to move the char * pointer from the first address to the next one, until it arrives at '\0'. So the empty string in Java is just a char * pointer immediately followed by '\0'.

Related